NSWindowController cannot capture ESC without adding WebView to window

I am subclassing NSWindowController from File-> New and with the option "With XIB for user interface". Therefore, I create 3 new files. Then I use Interface Builder to add only one view to the window.

And this code in MyWindowController.m:

- (void)keyDown:(NSEvent *)theEvent{ NSLog(@"%@", theEvent); } 
  • First test, add one NSButton and run the project.
  • Second test, add one WebView (NSButton deleted) and run the project.

In both tests, the window displays correctly. But the difference is:

  • (NSButton) I can see the log output when I press keys like "a", "b", ..., but not the ESC key
  • (WebView) I can see the log output when I press keys like "a", "b", ..., and the ESC key also

I am changing NSButton to a different type of view, as well as my custom view, all act as the first case.

My question is:

  • Why can't NSWindowController grab the ESC key in the first case?
  • Why NSWindowController grabs the ESC key using WebView as the first responder.
  • How can NSWindowController grab an ESC key without a WebView?
+4
source share
3 answers

See NSResponder cancelOperation: docs: https://developer.apple.com/library/mac/ipad/#documentation/Cocoa/Reference/ApplicationKit/Classes/NSResponder_Class/Reference/Reference.html

This method is associated with Escape and Command-. (period). the key window first looks for the view hierarchy for the view whose key is the equivalent of Escape or Command-., depending on what was entered. If none of these views processes the key equivalent, the window sends a default message on the cancelOperation action: to the first responder and from there the message moves up the chain of responders. If no responder in the responder chain implements cancelOperation :, the key window looks for the view hierarchy for the view whose key equivalent is Escape (note that this may be redundant if the original key equivalent was Escape). If no such responder is found, then the cancel: action message is sent to the first responder in the responder chain that it implements.

And if you want to handle the Esc key in your NSWindowController subclass, just define the cancel: method in it.

+6
source

Well, I use Event Monitor to capture the ESC key press, see details here: http://www.ideawu.com/blog/post/54.html

But still, don't get the WevView test.

0
source

I would suggest informing the window to make the interest the first responder interested, in order to catch key events

  [[self window]makeFirstResponder:_viewControllerOfInterest]; 
0
source

All Articles