要绑定到 1 键,我使用:
hs.hotkey.bind(hyper, '1'
如何绑定多次按 1 键?类似的东西:
hs.hotkey.bind(hyper, '1+1'
阅读the documentation,未提及此功能。
多次按下我的意思是按1
两次以运行一些代码并按1
三次以运行单独的代码。
答案 0 :(得分:0)
您无法使用bind绑定所有键或多个键。相反,您可以使用此功能:http://www.hammerspoon.org/docs/hs.eventtap.html#keyStroke
因此,最直接的编程语言不可知方法如下:
额外的极端条件:
答案 1 :(得分:0)
您必须自己实施此操作。以下是如何完成此任务的基本摘要:
hs.eventtap
,特别是hs.eventtap.event.types.keyPress
keyPress
)发生时,检查按下的键是否是正确的键翻译成代码,这是可能的样子(我不是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
为了更好地理解,我逐行对代码进行了评论。如果你想检测3或4或其他任意N次按下,只需设置N-1按下的标志并添加一些检查,但是按键组合需要连续按两次以上是不常见的。它似乎有点冗长,但AFAIK就是这样做的。为避免重复的代码和样板,请尝试将其放在类似于类的结构或模块中,以便可以重用代码。
至于为连续2次按下或连续3次按下执行不同的处理程序,这样会更加hacky,因为在知道用户是否再次按下以知道要执行哪个处理程序之前,您必须等待整个时间范围。这会导致轻微的延迟和糟糕的用户体验,我建议不要这样做,尽管你可以通过重构代码并进行更多检查来实现,例如,如果它的时间范围和第一个标志被触发,然后执行一次按下处理程序。