Search code examples
macoscocoakeydownnstextfield

Capture option / command key inside NSTextField


I have a NSTextField used in a NSViewController. I would like to capture special keyboard shortcuts like ⌥+0 to do something special. However these key events don't get delivered to:

- (BOOL) control:(NSControl *)control textView:(NSTextView *)textView doCommandBySelector:(SEL)commandSelector

I know we can't override the keyDown event for a custom NSTextField since a special field editor is used in place of our field anyway. How do I handle these special shortcuts without resorting to adding hidden NSMenuItems in the main menu?


Solution

  • What looks like a simple thing to do, apparently isn't on the Mac. Using a custom NSFormatter wouldn't work since I wanted to capture every keystroke (including modifier keys). The two options at hand were to either intercept sendEvent at the NSWindow level and bubble it up to the view controller hosting the focused control, or using a custom field editor. I ended up returning a custom field editor for the NSTextField (by subclassing NSTextField / NSTextFieldCell and returning a subclassed NSTextView object for the field editor). This way, I was able to cleanly, using delegates, intercept keystrokes and pass them to the view controller to be processed. Keystrokes that would not be consumed would otherwise be processed normally by the field editor.