I have a webpage that needs to receive keypresses to zoom and scroll. This seems to be the only way to prevent the annoying NSBeep from occurring. Return true too much, and command keys stop working. So need to be explicit about which keys you want. Also no way to block delete/shift+delete from going fwd/back in the history using this same mechanism.
func isKeyHandled(_ event: NSEvent) -> Bool {
// can't block delete or shift+delete
// so the WKWebView goes back/foward through it's 1 page history.
// that loses all context for the user.
// prevent super annoying bonk/NSBeep
// if don't check modifier flags (can't check isEmpty since 256 is often set
// then the cmd+S stops working
if !(event.modifierFlags.contains(.command) ||
event.modifierFlags.contains(.control) ||
event.modifierFlags.contains(.option)) {
// wasd
if event.keyCode == Keycode.w || event.keyCode == Keycode.a || event.keyCode == Keycode.s || event.keyCode == Keycode.d {
return true
}
}
return false
}
// Apple doesn't want this to be overridden by user, but key handling
// just doesn't work atop the WKWebView without this. KeyUp/KeyDown
// overrides don't matter, since we need the WKWebView to forward them
override func performKeyEquivalent(with event: NSEvent) -> Bool {
if !isKeyHandled(event) {
return super.performKeyEquivalent(with: event)
}
return true
}