在 Swift 中制作一次 keydown NSEvent 运行

Make keydown NSEvent run once in Swift

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

    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
}

如果您只是想摆脱按键声音,您需要将 return 类型更改为可选,并且 return 无:

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
}