4

I have a problem with my OpenGL Cocoa application - every time a keyUp / KeyDown event is fired, a system sound is being played... How can I disable this logic for my application?

I have a bad feeling that for some strange reason my application may treat a key press as an error and play system alert sound... Please help!

derhass
  • 43,833
  • 2
  • 57
  • 78
Ryan
  • 1,451
  • 2
  • 27
  • 36
  • Have you seen NSSound class references? '- (void)setVolume:(float)volume' – Parag Bafna Nov 03 '11 at 09:46
  • That's interesting, however this is not a static method and I can't disable all sounds with it... My application doesn't use Cocoa audio services in any way... – Ryan Nov 03 '11 at 11:40

4 Answers4

5

add to your NSView/NSWindow subclass

- (void)keyDown:(NSEvent *)theEvent {

and make exception on up and down keys, but for other [super keyDown:theEvent];

i think it's may sense

Volodymyr B.
  • 3,369
  • 2
  • 30
  • 48
4

For me, the following has turned out to be the optimal solution:

override func awakeFromNib() { 

    // Do your setup here.    

    NSEvent.addLocalMonitorForEvents(matching: .keyDown) {
       if keyDownPressed(with: $0) {
          return nil
       }
       return $0
    }
}

func keyDownPressed(with event: NSEvent) -> Bool {

    print("caught a key down: \(event.keyCode)")

    if event.keyCode == 125 {
        //your code for arrow down here
        return true
    }

    if event.keyCode == 126 {
        //your code for arrow up here
        return true
    }

    return false
}
user8675
  • 657
  • 6
  • 13
0
  1. Create a Cocoa Class, subclassing it from NSView
  2. Set it as the class for your View instead of standard greyed-out NSView in storyboard
  3. Add the following to your subclass implementation:
@implementation YourCustomNSView

- (BOOL)acceptsFirstResponder {
    return YES;
}

- (void)keyDown:(NSEvent *)theEvent {

    NSLog (@"keypress %@", theEvent);
//    [super keyDown:theEvent]; // this line triggers system beep error, there's no beep without it
}

@end
Igor Kroitor
  • 1,548
  • 13
  • 16
0

Swift 5.6 solution

It's caused because of unhandled keydown events in your responder chain.

Make sure some NSView subclass in your responder chain overrides this and returns true.

override performKeyEquivalent(with event: NSEvent) -> Bool {}
arthas
  • 680
  • 1
  • 8
  • 16