I bet sometimes you needed keyboard’s arrow (directions) key’s callback in your app. At least that was scenario I faced just few days ago… Like any other cocoa developerI though keyDown:(NSEvent *)theEvent or keyUp:(NSEvent *)theEvent will do the trick but I was thinking wrong.
It turns out that NSResponder’s methods don’t pass single direction key’s events. Ok, never mind – I thought for a moment. I have a backup solution. Backup solution was to set direction key’s events as NSMenuItem’s key equivalent property and connect them via IBAction with code implementation.
Again, I was on wrong path… This solution works perfect fine if you want to reserve direction keys events just for one action and bypass all default actions. In my situation I needed this event for various new as well as default actions (like moving text cursor in search field). And then it suddenly cross my mind (to be honest after asking google) that I can solve this issue by passing code block via NSEvent addLocalMonitorForEventsMatchingMask: class method. See code snippet bellow.
[NSEvent addLocalMonitorForEventsMatchingMask: NSKeyDownMask handler: ^(NSEvent *event) { BOOL isTextFieldActive = NO; NSResponder *firstResponder = [[NSApp keyWindow] firstResponder]; if ([firstResponder isKindOfClass:[NSText class]]) { isTextFieldActive = YES; } if (!isTextFieldActive) { // Here goes your code implementation } return event; }];
It works for me. Hope it helps you. Cheers!