Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KeyDown and Cocoa Sample

I'm learning how to build programs with Cocoa. I'm using a sample Apple application that records video from a webcam. I'd like to start and stop the video by capturing the key press. I've tried to override the keydown event but I've read that it's not possible in an NSObject. How can I handle this kind of event?

The class of application extends a NSObject class.

This is the code:

- (void)keyDown:(NSEvent *)event {
  NSLog(@"Hi there");
  NSString *characters = [event characters];
  if ([characters length]) {
    switch ([characters characterAtIndex:0]) {
      case NSUpArrowFunctionKey:
      NSLog(@"Key UP");
      break;
    }
  }
}
like image 702
Andrea Girardi Avatar asked Jul 17 '09 15:07

Andrea Girardi


1 Answers

I've tried to override Keydown event but I've read that It's not possible in an NSObject.

Correct. Only a responder can respond to events.

How can I handle this kind of event?

Implement a responder. Subclassing NSWindow or NSWindowController will work. Make sure you make your actual window or window controller an instance of your subclass.

The Cocoa documentation explains further.

The class of application extends a NSObject class.

Why? Normally, the principal class of the application bundle is NSApplication or a subclass of that—and there aren't many good reasons to subclass NSApplication.

PS: What's a very good book to start learn MacOS Programming?

I didn't learn by the Hillegass book, myself (I stuck to Apple's docs), but it's a very popular recommendation and I have read it and can tell you it's good.

like image 147
Peter Hosey Avatar answered Oct 06 '22 06:10

Peter Hosey