
使用 Applescript 监听键盘并识别特定按键
本文介绍如何利用 Applescript 监控键盘输入并检测特定按键。核心方法是使用 key code 属性。
以下代码演示了监听键盘事件并识别特定按键(例如,数字键“0”):
-- 键盘事件处理程序
on handleKeyboardEvents(theEvent)
-- 获取事件类型
set theEventType to theEvent's event type
-- 判断是否为按键按下事件
if theEventType is "down" then
-- 获取按键代码
set theKeyCode to theEvent's key code
-- 检查是否为目标按键 (此处为数字键 "0", key code 为 48)
if theKeyCode is 48 then
-- 执行相应操作 (例如,显示警告框)
display alert "您按下了数字键 0。"
end if
end if
end handleKeyboardEvents
-- 开始监听键盘事件
on run
add handler handleKeyboardEvents to application events
end run
这段代码首先定义了一个 handleKeyboardEvents 事件处理程序,该程序接收键盘事件作为参数。它检查事件类型是否为 "down" (按键按下),然后获取按键的 key code。最后,它检查 key code 是否与目标按键 (此处为 48,代表数字键“0”) 相匹配,如果匹配则执行指定的操作。run 部分则添加了事件处理程序到应用程序事件中,从而开始监听键盘事件。 您可以根据需要修改 theKeyCode is 48 部分来检测其他按键。 请注意,不同的按键拥有不同的 key code 值。










