本文目录导读:

- Linux 环境(AutoKey 脚本)
- Windows(AutoHotkey 脚本)
- macOS(Hammerspoon 脚本)
- 跨平台 Python 脚本(使用 pynput)
- 配置文件方式(YAML 格式)
- 使用说明
我来为您提供几种实现键盘快捷键映射的脚本方案,覆盖不同操作系统和使用场景。
Linux 环境(AutoKey 脚本)
# ~/.config/autokey/data/MyScripts/shortcuts.py
# 需要安装 AutoKey: sudo apt install autokey-gtk
import time
# Ctrl+Alt+T → 打开终端
keyboard.send_keys("<ctrl>+<alt>+t")
# 或者自定义快捷键组合
def on_hotkey():
# Windows 键 + E → 打开文件管理器
keyboard.send_keys("<super>+e")
# Ctrl+Shift+V → 粘贴纯文本
keyboard.send_keys("<ctrl>+<shift>+v")
# 特定应用程序中的快捷键
def in_terminal():
"""在终端中 Ctrl+Shift+C 复制"""
keyboard.send_keys("<ctrl>+<shift>+c")
Windows(AutoHotkey 脚本)
; shortcuts.ahk - AutoHotkey 快捷键映射脚本
; 下载: https://www.autohotkey.com/
#NoEnv
#SingleInstance Force
; --- 系统快捷键 ---
; Win+E → 打开文件管理器
#e::
Run, explorer.exe
Return
; Ctrl+Alt+T → 打开终端
^!t::
Run, cmd.exe
Return
; --- 文本编辑快捷键 ---
; Ctrl+Shift+V → 粘贴纯文本
^+v::
PastePlain()
Return
PastePlain() {
ClipSaved := ClipboardAll
Clipboard := ""
Send, ^c
Sleep, 50
Clipboard := Clipboard
Send, ^v
Sleep, 50
Clipboard := ClipSaved
}
; --- 窗口管理 ---
; Win+↑ → 最大化窗口
#Up::
WinMaximize, A
Return
; Win+↓ → 最小化窗口
#Down::
WinMinimize, A
Return
; --- 媒体按键 ---
; Ctrl+Alt+→ → 下一曲
^!Right::
Send, {Media_Next}
Return
; Ctrl+Alt+← → 上一曲
^!Left::
Send, {Media_Prev}
Return
; Ctrl+Alt+Space → 播放/暂停
^!Space::
Send, {Media_Play_Pause}
Return
; --- 鼠标快捷键 ---
; XButton1 (鼠标侧键) → 复制
XButton1::
Send, ^c
Return
; XButton2 (鼠标侧键) → 粘贴
XButton2::
Send, ^v
Return
; 程序特定快捷键
#IfWinActive, ahk_class Notepad
; 在记事本中 Ctrl+Q 退出
^q::
Send, !{F4}
Return
#IfWinActive
macOS(Hammerspoon 脚本)
-- ~/.hammerspoon/init.lua
-- 安装: brew install hammerspoon
-- 加载辅助功能权限
hs.loadSpoon("ControlEscape")
-- 定义快捷键映射
local hotkeys = {
-- 应用程序快捷键
{ {"cmd", "alt"}, "T", function()
hs.application.launchOrFocus("Terminal")
end},
-- 窗口管理
{ {"cmd", "alt"}, "H", function()
hs.window.focusedWindow():moveToUnit(hs.layout.left50)
end},
{ {"cmd", "alt"}, "L", function()
hs.window.focusedWindow():moveToUnit(hs.layout.right50)
end},
{ {"cmd", "alt", "shift"}, "H", function()
hs.window.focusedWindow():moveToUnit(hs.layout.maximized)
end},
-- 剪贴板历史
{ {"cmd", "shift"}, "V", function()
hs.eventtap.keyStrokes(hs.pasteboard.getContents())
end},
-- 快速打开应用
{ {"cmd", "alt"}, "F", function()
hs.application.launchOrFocus("Finder")
end},
{ {"cmd", "alt"}, "C", function()
hs.application.launchOrFocus("Calculator")
end},
}
-- 注册所有快捷键
for _, hotkey in ipairs(hotkeys) do
hs.hotkey.bind(unpack(hotkey))
end
-- 状态菜单
hs.menubar.new():setTitle("⌨️")
-- 屏幕亮度调节
hs.hotkey.bind({"cmd", "alt"}, "Up", function()
hs.brightness.set(hs.brightness.get() + 0.1)
end)
hs.hotkey.bind({"cmd", "alt"}, "Down", function()
hs.brightness.set(hs.brightness.get() - 0.1)
end)
-- 音量控制
hs.hotkey.bind({"cmd", "alt"}, "Right", function()
hs.audiodevice.defaultOutputDevice():setVolume(
hs.audiodevice.defaultOutputDevice():volume() + 0.05
)
end)
hs.hotkey.bind({"cmd", "alt"}, "Left", function()
hs.audiodevice.defaultOutputDevice():setVolume(
hs.audiodevice.defaultOutputDevice():volume() - 0.05
)
end)
跨平台 Python 脚本(使用 pynput)
# keyboard_mapper.py
# 安装: pip install pynput
from pynput import keyboard
import subprocess
import os
import sys
class KeyboardMapper:
def __init__(self):
self.current_keys = set()
self.listener = keyboard.Listener(
on_press=self.on_press,
on_release=self.on_release
)
# 定义快捷键映射
self.shortcuts = {
# (修饰键组合, 触发键): 执行函数
(frozenset([keyboard.Key.ctrl, keyboard.Key.alt]), 't'): self.open_terminal,
(frozenset([keyboard.Key.ctrl, keyboard.Key.alt]), 'f'): self.open_finder,
(frozenset([keyboard.Key.ctrl, keyboard.Key.shift]), 'v'): self.paste_plain,
}
def on_press(self, key):
try:
self.current_keys.add(key)
self.check_shortcut()
except Exception as e:
print(f"Error: {e}")
def on_release(self, key):
try:
if key in self.current_keys:
self.current_keys.remove(key)
except:
pass
def check_shortcut(self):
# 获取当前按下的修饰键
modifiers = frozenset(k for k in self.current_keys
if k in [keyboard.Key.ctrl, keyboard.Key.alt,
keyboard.Key.shift, keyboard.Key.cmd])
# 获取最后一个按下的非修饰键
non_modifiers = [k for k in self.current_keys
if k not in [keyboard.Key.ctrl, keyboard.Key.alt,
keyboard.Key.shift, keyboard.Key.cmd]]
if non_modifiers:
last_key = non_modifiers[-1]
try:
if hasattr(last_key, 'char'):
key_char = last_key.char
else:
key_char = str(last_key).replace('Key.', '')
shortcut_key = (modifiers, key_char)
if shortcut_key in self.shortcuts:
self.shortcuts[shortcut_key]()
except Exception as e:
print(f"Shortcut error: {e}")
def open_terminal(self):
if sys.platform == 'linux':
subprocess.run(['x-terminal-emulator'])
elif sys.platform == 'darwin':
subprocess.run(['open', '-a', 'Terminal'])
elif sys.platform == 'win32':
subprocess.run(['cmd.exe'])
def open_finder(self):
if sys.platform == 'darwin':
subprocess.run(['open', '.'])
elif sys.platform == 'win32':
subprocess.run(['explorer.exe'])
def paste_plain(self):
if sys.platform == 'linux':
subprocess.run(['xdotool', 'key', '--clearmodifiers', 'ctrl+v'])
def start(self):
print("Keyboard mapper started. Press Ctrl+Alt+T to test.")
with self.listener:
self.listener.join()
if __name__ == "__main__":
mapper = KeyboardMapper()
mapper.start()
配置文件方式(YAML 格式)
# shortcuts.yml
# 通用快捷键配置文件
shortcuts:
application:
- hotkey: "Ctrl+Alt+T"
action: "open_terminal"
description: "打开终端"
- hotkey: "Win+E"
action: "open_file_manager"
description: "打开文件管理器"
- hotkey: "Ctrl+Shift+V"
action: "paste_plain_text"
description: "粘贴纯文本"
window:
- hotkey: "Win+Up"
action: "maximize_window"
description: "最大化窗口"
- hotkey: "Win+Down"
action: "minimize_window"
description: "最小化窗口"
- hotkey: "Win+Left"
action: "snap_left"
description: "窗口靠左"
- hotkey: "Win+Right"
action: "snap_right"
description: "窗口靠右"
media:
- hotkey: "Ctrl+Alt+Right"
action: "next_track"
description: "下一曲"
- hotkey: "Ctrl+Alt+Left"
action: "prev_track"
description: "上一曲"
- hotkey: "Ctrl+Alt+Space"
action: "play_pause"
description: "播放/暂停"
# 自定义映射
custom_mappings:
- from: "CapsLock"
to: "Ctrl"
description: "CapsLock 映射为 Ctrl"
- from: "RightAlt"
to: "Shift"
description: "右 Alt 映射为 Shift"
使用说明
选择建议:
- Windows 用户 → AutoHotkey(最成熟、功能最全)
- macOS 用户 → Hammerspoon(Lua 脚本,灵活强大)
- Linux 用户 → AutoKey(Python 脚本)或 xdotool
- 跨平台需求 → Python + pynput
快速开始:
# AutoHotkey(Windows) # 1. 安装 AutoHotkey # 2. 创建 .ahk 文件并粘贴脚本 # 3. 双击运行 # Hammerspoon(macOS) # 1. 安装: brew install hammerspoon # 2. 创建 ~/.hammerspoon/init.lua # 3. 重新加载配置 # Python 跨平台 pip install pynput python keyboard_mapper.py
注意事项:
- 避免与系统或软件已有的快捷键冲突
- 在 macOS 上需要授权辅助功能权限
- 管理员权限可能需要在 Windows 上运行某些操作
- 定期备份配置文件
需要针对特定场景或操作系统做更详细的定制吗?