Jesus
Jesus

Reputation: 8586

How to use keyDown in NSObjectController

I'm developing an ap for MacOSX with Xcode5

my initial window is NSObjectController based, and I'm trying to capture keyboard events by using the common method I used on NSWindowControllers called

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

but this doesn't captures anything... is there any other method for such task????

thanks in advance for the support

Upvotes: 1

Views: 69

Answers (1)

Jesús Ayala
Jesús Ayala

Reputation: 2791

there's another way to get it work on NSObjectController...

this captures left key and right key for instance....

@interface MyNSObjectController(){
    id          eventMonitor; 
}

@end

@implementation MyNSObjectController
- (void) awakeFromNib{
    [self captureKeyDownEvents];
}

-(void)captureKeyDownEvents{
    NSEvent  *(^handler)(NSEvent*)  = ^(NSEvent *theEvent) {
        NSObjectController *targetWindow          = self;
        if (targetWindow != self) {
            return theEvent;
        }

        NSEvent *result = theEvent;
        if (theEvent.keyCode == 123) { //left arrow
            NSLog(@"you just pressed left key");
            result = nil;
        }

        if (theEvent.keyCode == 124) { //right arrow
            NSLog(@"you just pressed right key");
            result = nil;
        }

        return result;
    };
    eventMonitor = [NSEvent addLocalMonitorForEventsMatchingMask:NSKeyDownMask handler:handler];
}

-(void)dealloc{
    [NSEvent removeMonitor:eventMonitor];
}

@end

Upvotes: 1

Related Questions