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
}