让keydown NSEvent在Swift中运行一次



NSEvent keydown代码在按下键时重复运行。如何确保事件只运行一次,然后停止侦听,直到key up事件发生?

override func viewDidLoad() {
super.viewDidLoad()
NSEvent.addLocalMonitorForEvents(matching: .keyDown, handler: doSomething(event:))
}

func doSomething(event: NSEvent) -> NSEvent{
// 36 is key code for ENTER key 
if event.keyCode == 36{
print("Hello World!")
}
return event
}

您可以使用isARepeat属性简单地检查NSEvent是否为重复:

func doSomething(event: NSEvent) -> NSEvent {
if event.keyCode == 36, !event.isARepeat {
print("Hello World!")
}
return event
}

如果你只是想摆脱键的声音,你需要改变你的返回类型为可选,并返回nil:

func doSomething(event: NSEvent) -> NSEvent? {
guard !event.isARepeat else {
// this will suppress the key sound if you return nil and not propagate the key down event
return nil
}
if event.keyCode == 36 {
print("Hello World!")
// if you want to suppress the key sound when is not a repeat just return nil here as well
return nil
}

return event
}

相关内容

  • 没有找到相关文章

最新更新