用脚本实现自定义快捷键

wen 实用脚本 2

本文目录导读:

用脚本实现自定义快捷键

  1. 方式一:使用 AutoHotkey(Windows)
  2. 方式二:使用 Python + pynput
  3. 方式三:使用 JavaScript(浏览器环境)
  4. 使用说明
  5. 常用快捷键符号:

我来帮您创建一个自定义快捷键脚本,这里提供两种常见方式:

使用 AutoHotkey(Windows)

创建一个 .ahk 文件:

; 自定义快捷键脚本
; 保存为 custom_shortcuts.ahk
; 基础快捷键示例
#z::  ; Win + Z
    Run, notepad.exe
return
#q::  ; Win + Q 打开计算器
    Run, calc.exe
return
; 粘贴纯文本
^+v::  ; Ctrl + Shift + V
    SendInput, ^v
return
; 快速输入常用文本
::addr::北京市朝阳区某某街道100号  ; 输入"addr"后自动替换
::email::your.email@example.com
::phone::138-0000-0000
; 窗口管理
#up::  ; Win + ↑ 窗口最大化
    WinMaximize, A
return
#down::  ; Win + ↓ 窗口还原/最小化
    WinRestore, A
    WinMinimize, A
return

使用 Python + pynput

# custom_shortcuts.py
from pynput import keyboard
import os
import subprocess
class CustomShortcuts:
    def __init__(self):
        self.current_keys = set()
        self.listener = keyboard.Listener(
            on_press=self.on_press,
            on_release=self.on_release
        )
    def on_press(self, key):
        try:
            # 处理普通按键
            if hasattr(key, 'char') and key.char:
                self.current_keys.add(key.char.lower())
            else:
                self.current_keys.add(key)
            # 判断快捷键组合
            if self.check_combination(keyboard.Key.ctrl_l, 'c'):
                print("触发了 Ctrl+C")
                # 执行自定义操作
            elif self.check_combination(keyboard.Key.ctrl_l, keyboard.Key.shift, 'a'):
                print("触发了 Ctrl+Shift+A")
                subprocess.run(["notepad.exe"])
            elif self.check_combination(keyboard.Key.alt_l, 'z'):
                print("触发了 Alt+Z")
                os.system("calc")
        except Exception as e:
            print(f"错误: {e}")
    def on_release(self, key):
        try:
            if hasattr(key, 'char') and key.char:
                self.current_keys.discard(key.char.lower())
            else:
                self.current_keys.discard(key)
        except:
            pass
    def check_combination(self, *keys):
        """检查是否所有需要的键都被按下"""
        required_keys = set(keys)
        return required_keys.issubset(self.current_keys)
    def start(self):
        print("自定义快捷键脚本运行中...按 ESC 退出")
        with self.listener:
            self.listener.join()
if __name__ == "__main__":
    shortcuts = CustomShortcuts()
    shortcuts.start()

使用 JavaScript(浏览器环境)

// 浏览器快捷键脚本 (油猴脚本或控制台使用)
(function() {
    'use strict';
    // 快捷键映射
    const shortcuts = {
        'ctrl+shift+z': () => {
            console.log('触发了 Ctrl+Shift+Z');
            // 执行自定义操作
        },
        'alt+x': () => {
            // 打开某个页面
            window.open('https://example.com');
        },
        'ctrl+q': {
            description: '快速跳转到底部',
            action: () => window.scrollTo(0, document.body.scrollHeight)
        }
    };
    document.addEventListener('keydown', function(event) {
        // 构建快捷键字符串
        const keys = [];
        if (event.ctrlKey) keys.push('ctrl');
        if (event.shiftKey) keys.push('shift');
        if (event.altKey) keys.push('alt');
        if (event.metaKey) keys.push('meta');
        const key = event.key.toLowerCase();
        if (key !== 'control' && key !== 'shift' && key !== 'alt' && key !== 'meta') {
            keys.push(key);
        }
        const shortcutStr = keys.join('+');
        // 检查是否有匹配的快捷键
        if (shortcuts[shortcutStr]) {
            event.preventDefault();
            if (typeof shortcuts[shortcutStr] === 'function') {
                shortcuts[shortcutStr]();
            } else if (shortcuts[shortcutStr].action) {
                shortcuts[shortcutStr].action();
            }
        }
    });
    // 显示已注册的快捷键
    console.log('已注册的快捷键:', Object.keys(shortcuts));
})();

使用说明

AutoHotkey 方式:

  1. 安装 AutoHotkey
  2. 创建 .ahk 文件并粘贴代码
  3. 双击运行脚本

Python 方式:

# 安装依赖
pip install pynput
# 运行脚本
python custom_shortcuts.py

JavaScript 方式:

  1. 安装 Tampermonkey 插件
  2. 创建新脚本并粘贴代码
  3. 保存并启用

常用快捷键符号:

  • = Win 键
  • = Ctrl 键
  • = Shift 键
  • = Alt 键

您可以根据需要修改和扩展这些脚本,需要更多帮助吗?

抱歉,评论功能暂时关闭!