1
votes

I'm trying to bind a bare esc key press to an NSMenuItem that toggles full screen (currently just a stub function). Manually selecting the menu item sends the desired IBAction. When I set the NSMenuItem's Key Equiv. in Interface Builder to an arbitrary bare key (eg. w) that key command sends the desired IBAction. When I set the Key Equiv. to command + esc, that key command sends the desired IBAction. But a bare esc key press is ignored.

I'm assuming the esc key is special-cased. Other applications (eg. Bannister's various emulators) are able to achieve this, any idea how?

3

3 Answers

3
votes

I'm no Objective-C veteran, so apologies if I'm misunderstanding the question. But have you tried moving up the responder chain and grabbing the keyDown event in NSWindow? Something like:

- (void)keyDown: (NSEvent *) event {
   if ([event keyCode] == 53) {
        NSLog(@"Esc. pressed");
     }
}

Of course, this solution will require that you subclass NSWindow.

2
votes

The Escape key is tightly bound to the cancelOperation class of NSResponder.

Try to subclass your NSWindow and give it this method:

- (void)cancelOperation:(id)sender {
  if (![SomeController doSomeAction]) {
    [super cancelOperation:sender];
  }
}

Your window will then react to the Escape key and evoke doSomeAction. That would be the method your NSMenuItem would have liked to call, but it refused to do so :)

In the doSomeAction method you should return a Boolean that indicates whether the action did actually do something. If it did, good. If it did not (and returned NO), your NSWindow will pass on the Escape key event to the next responder in the chain.

I like this solution because it gives the user audio feedback about whether his key press actually did something. Because if your method didn't do anything, and no other repsonder did do anything, there will be some "beep" sound.

Note that in an NSView without an attached window, you might have to use [self nextResponder] instead of super.

0
votes

Please have a look at http://developer.apple.com/mac/library/documentation/UserExperience/Conceptual/AppleHIGuidelines/XHIGUserInput/XHIGUserInput.html “… The Esc (Escape) key basically means “let me out of here.” It has specific meanings in certain contexts. The user can press Esc in the following situations: …”

Greetings