Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OSX swift 3 - can't disable keyDown. error sound

Tags:

macos

swift

Im am trying to disable error sound when I push down space bar and arrow keys. I tryed handling events with super.keyDown(with: event) no luck. Cant find any other working solutions apart from using global key frameworks. Are there any other options I have?

   NSEvent.addLocalMonitorForEvents(matching: .keyDown) { (aEvent) -> NSEvent? in
        self.keyDown(with: aEvent)
        return aEvent
    }

}

override func keyDown(with event: NSEvent) {
    super.keyDown(with: event)

}
like image 790
Swifless Avatar asked Jan 04 '23 01:01

Swifless


1 Answers

Update: I've found out that the root cause of the problem was, that a view was the first responder that shouldn't be actually. After setting the responder to nil self.view.window?.makeFirstResponder(nil) I was able to fix this. I've also used performKeyEquivalent as this answer suggested.

I know my answer is very late, but maybe it will help you or someone else in the future. I'm not sure if that's the best way to do it but it does work. Simply return nil instead of the event.

NSEvent.addLocalMonitorForEvents(matching: .keyDown) { (aEvent) -> NSEvent? in
    self.keyDown(with: aEvent)
    return nil
}

override func keyDown(with event: NSEvent) {
    super.keyDown(with: event)
}

Apple's documentation of the method says the following for the block parameter:

The event handler block object. It is passed the event to monitor. You can return the event unmodified, create and return a new NSEvent object, or return nil to stop the dispatching of the event.

The only downside is, that there will be no sound at all. Even if the key event is not handled by you.

like image 81
Brudus Avatar answered Jan 05 '23 16:01

Brudus