Search code examples
cocoahotkeys

Add HotKey to NSTextField


I have some trouble with my NSTextField subclass. It's a textfield for input some message. And My application must send this message when my sub-textfield is a first responder and the user presses hotkey Cmd + Enter. I can't use Carbon method RegisterEventHotKey() because many applications use this hotkey for the same action but my application intercepts it. What can I do?


Solution

  • I subclassed NSApplication and override method

    - (void) sendEvent:(NSEvent*) event {
        if ([event type] == NSKeyDown) {
            if (([event modifierFlags] & NSDeviceIndependentModifierFlagsMask) == NSCommandKeyMask) {
                if ([event keyCode] == 36) {
                    if ([self.delegate respondsToSelector:@selector(sendMessage:)]) {
                        [self.delegate performSelector:@selector(sendMessage:) withObject:nil];
                    }
                }
            }
        }
    
        [super sendEvent:event];
    }
    

    in info.plist I wrote that this sub-NSApplication class is a Principal class. It works!