Sunday, May 16, 2010

Cocoa Tip: Detecting Arrow Down Key Events

We all know the Spotlight Search item in the top right corner of the screen. You can enter something and Spotlight instantly finds all matching files. The results view below the search field can be accessed by pressing the down arrow key. Usually pressing the down arrow key has the effect that the cursor jumps to the end of the text field's content. How can we override the default behavior? One solution would be to subclass NSTextView and provide an instance of this text view as the field editor of the cell. Luckily we have an alternative solution for this:

   [NSEvent addLocalMonitorForEventsMatchingMask:NSKeyDownMask handler:^(NSEvent *event) {
      NSString *characters = [event characters];
      unichar character = [characters characterAtIndex:0];
      if(character == NSDownArrowFunctionKey) {
         NSLog(@"key down");
      return event;

This solution looks pretty straight forward. We could also return an alternative event. I don't want to say that this is my final solution but I am happy to see that common things are easy with Cocoa.

Edit: You can remove a monitor by calling +removeMonitor: (NSEvent).