Is there something wrong with binding a menu item to the Esc key?

Discussion in 'Mac Programming' started by BadWolf13, May 19, 2010.

  1. BadWolf13 macrumors 6502

    Dec 17, 2009
    Working in Objective C, X-Code, and I made the keyboard shortcut for a menu item as the "esc" key. It's not working. Is there something inherent that is going to prevent me from using that key? First off, the active window is an NSWindow, not an NSPanel, so the escape key isn't used for closing the window. Does anyone have any thoughts as to why this isn't working?
  2. gnasher729 macrumors P6


    Nov 25, 2005
    "Esc" is probably caught much earlier and never makes it to the menu code. If it would work, it would be an awful idea, because the escape key is used in lots of places in the UI.
  3. kainjow Moderator emeritus


    Jun 15, 2000
    Have a look at the documentation for -[NSResponder cancelOperation:] - essentially if a window is active it takes over control for the escape key. If the window isn't active it looks like it works fine.

    Using cancelOperation: is probably the best way to go since it's documented. However I hacked something together that makes it work by overriding -[NSApplication sendEvent:].

    - (void)sendEvent:(NSEvent *)anEvent
        NSString *escKeyEquivalent = [NSString stringWithFormat:@"%c", 27];
        if ([anEvent type] == NSKeyDown && [[anEvent characters] isEqualToString:escKeyEquivalent])
            if ([[self mainMenu] performKeyEquivalent:anEvent])
        [super sendEvent:anEvent];
    I would not ship with that though :)
  4. BadWolf13 thread starter macrumors 6502

    Dec 17, 2009
    Yeah, that hack is a bit complicated. What I ended up doing was overriding the cancel: method. Seemed the simplest way of doing it.
  5. Detrius macrumors 68000

    Sep 10, 2008
    Asheville, NC
    By overriding the cancel method, you'll likely get command-period functionality, too, since that was originally the way to cancel anything in Classic.
  6. BadWolf13 thread starter macrumors 6502

    Dec 17, 2009
    As I understand the documentation, cancelOperation: gives me esc and command-period functionality, but cancel: just gives me esc functionality. Frankly, that's what I was looking for, so I just changed my method from cancelEdit: to cancel:. Not really all that complicated, eh?

Share This Page