插件窝 干货文章 Applescript如何监听键盘按键并执行特定操作?

Applescript如何监听键盘按键并执行特定操作?

监听 事件 键盘 执行 262    来源:    2025-03-13

在AppleScript中,你可以使用System Events来监听键盘按键并执行特定操作。以下是一个简单的示例,展示了如何监听特定的按键并执行相应的操作。

示例:监听 Command + Shift + A 组合键并执行操作

-- 导入必要的框架
use framework "Foundation"
use framework "AppKit"

-- 定义一个全局变量来存储事件监视器
property eventMonitor : missing value

-- 启动监听
on startListening()
    -- 使用NSEvent的addGlobalMonitorForEventsMatchingMask方法来监听全局事件
    set eventMonitor to current application's NSEvent's addGlobalMonitorForEventsMatchingMask:(current application's NSKeyDownMask) handler:(handler)
end startListening

-- 停止监听
on stopListening()
    if eventMonitor is not missing value then
        current application's NSEvent's removeMonitor:eventMonitor
        set eventMonitor to missing value
    end if
end stopListening

-- 处理按键事件的handler
on handler(theEvent)
    -- 获取按下的键
    set keyCode to theEvent's keyCode()
    set modifierFlags to theEvent's modifierFlags()

    -- 判断是否按下了Command + Shift + A
    if modifierFlags = (current application's NSCommandKeyMask + current application's NSShiftKeyMask) and keyCode = 0 then
        -- 执行特定操作
        display dialog "Command + Shift + A pressed!"
    end if
end handler

-- 启动监听
startListening()

-- 保持脚本运行以继续监听
repeat
    delay 1
end repeat

解释:

  1. use framework: 导入FoundationAppKit框架,以便使用NSEvent类来监听键盘事件。
  2. startListening: 使用NSEventaddGlobalMonitorForEventsMatchingMask方法来监听全局的键盘事件。
  3. handler: 这是一个回调函数,当有键盘事件发生时会被调用。在这个函数中,你可以检查按下的键和修饰键(如Command、Shift等),并根据需要执行操作。
  4. stopListening: 停止监听键盘事件。
  5. repeat: 保持脚本运行,以便继续监听键盘事件。

注意事项:

  • 这个脚本会监听全局的键盘事件,因此即使你的脚本不是当前焦点,它也会响应按键。
  • 你需要确保脚本有权限访问辅助功能(Accessibility),否则可能无法正常工作。你可以在“系统偏好设置” -> “安全性与隐私” -> “隐私” -> “辅助功能”中启用权限。

扩展:

你可以根据需要修改handler函数中的逻辑,以监听不同的按键组合并执行不同的操作。例如,你可以监听Command + Shift + B并执行另一个操作。

希望这个示例对你有帮助!