11

I'm hacking on a simple Cocoa app to make blocks move around the screen like a video game. I need to detect key presses, but I'm not going to have text entry fields like a dialog box would have.

How do I get key presses without text controls? In particular, I need to get arrow keys.

Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662

1 Answers1

14

In your game view, define the keyUp and keyDown methods:

@interface MyView : NSView
-(void)keyUp:(NSEvent*)event;
-(void)keyDown:(NSEvent*)event;
@end

@implementation MyView

-(void)keyUp:(NSEvent*)event
{
    NSLog(@"Key released: %@", event);
}

-(void)keyDown:(NSEvent*)event
{   
    // I added these based on the addition to your question :)
    switch( [event keyCode] ) {
        case 126:   // up arrow
        case 125:   // down arrow
        case 124:   // right arrow
        case 123:   // left arrow
            NSLog(@"Arrow key pressed!");
            break;
        default:
            NSLog(@"Key pressed: %@", event);
            break;
    }
}
@end

See the documentation for NSView and NSEvent for more info. Note that the keyDown and keyUp events are actually defined on NSResponder, the super class for NSView.

Jason Coco
  • 77,985
  • 20
  • 184
  • 180
  • 3
    Something to note, is that keyUp: and keyDown: do not get called if the user presses only a modifier key, such as shift, ctrl, alt or cmd. This is of course reasonable behavior for most apps, but possibly not for games. If you want your app to be notified when a modifier key is pressed, you can implement [flagsChanged:](http://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSResponder_Class/Reference/Reference.html#//apple_ref/occ/instm/NSResponder/flagsChanged:). – sarnesjo Apr 30 '11 at 21:06
  • See also [acceptsFirstResponder](http://stackoverflow.com/questions/7475394/nsopenglview-nswindow-nsresponder-makefirstresponder-not-working) – Jared Beck May 10 '14 at 16:04