要绑定到1我使用的键:
hs.hotkey.bind(hyper, '1'
Run Code Online (Sandbox Code Playgroud)
如何绑定多次1按键?就像是:
hs.hotkey.bind(hyper, '1+1'
Run Code Online (Sandbox Code Playgroud)
阅读文档,未提及此功能.
通过多次按下我的意思是按1两次以运行一些代码并按1三次以运行单独的代码.
您必须自己实现这一点。以下是如何实现此目的的基本摘要:
hs.eventtap,特别是hs.eventtap.event.types.keyPresskeyPress)发生时,检查按下的按键是否是正确的按键翻译成代码,这就是它的样子(我不是 Lua 专家)。请注意,这些标志可以在这里实现为布尔值,或者作为保存按键的内部表,您可以检查:
local timer = require("hs.timer")
local eventtap = require("hs.eventtap")
local keycodes = require("hs.keycodes")
local events = eventtap.event.types --all the event types
timeFrame = 1 --this is the timeframe in which the second press should occur, in seconds
key = 50 --the specific keycode we're detecting, in this case, 50
--print(keycodes.map["`"]) you can look up the certain keycode by accessing the map
function twoHandler()
hs.alert("Pressed ` twice!") --the handler for the double press
end
function correctKeyChecker(event) --keypress validator, checks if the keycode matches the key we're trying to detect
local keyCode = event:getKeyCode()
return keyCode == key --return if keyCode is key
end
function inTime(time) --checks if the second press was in time
return timer.secondsSinceEpoch() - time < timeFrame --if the time passed from the first press to the second was less than the timeframe, then it was in time
end
local pressTime, firstDown = 0, false --pressTime was the time the first press occurred which is set to 0, and firstDown indicates if the first press has occurred or not
eventtap.new({ events.keyDown }, function(event) --watch the keyDown event, trigger the function every time there is a keydown
if correctKeyChecker(event) then --if correct key
if firstDown and inTime(pressTime) then --if first press already happened and the second was in time
twoHandler() --execute the handler
elseif not firstDown or inTime(pressTime) then --if the first press has not happened or the second wasn't in time
pressTime, firstDown = timer.secondsSinceEpoch(), true --set first press time to now and first press to true
return false --stop prematurely
end
end
pressTime, firstDown = 0, false --if it reaches here that means the double tap was successful or the key was incorrect, thus reset timer and flag
return false --keeps the event propogating
end):start() --start our watcher
Run Code Online (Sandbox Code Playgroud)
为了更好地理解,我已经逐行注释了代码。如果您想检测 3 次或 4 次或其他任意 N 次按下,只需为 N - 1 次按下设置标志并添加一些检查,但连续按下 2 次以上的按键组合并不常见。这看起来确实有点冗长,但据我所知,这就是你的做法。为了避免重复的代码和样板文件,请尝试将其放入类似类的结构或模块中,以便可以重用代码。
至于为 2 次连续按下或 3 次连续按下执行不同的处理程序,这会有点麻烦,因为您必须等待整个时间范围才能知道用户是否会再次按下才能知道要执行哪个处理程序。这会导致轻微的延迟和糟糕的用户体验,我建议不要这样做,尽管您可能可以通过重构代码并进行更多检查来实现这一点,例如是否是时间范围以及第一个标志是否被触发,然后执行处理程序按一次。
| 归档时间: |
|
| 查看次数: |
566 次 |
| 最近记录: |