非NSResponder类捕捉按键消息

来源:互联网 发布:mac word 删除空白页 编辑:程序博客网 时间:2024/05/21 13:55

You may want to capture(or intercept, detect) the ESC key press in a Cocoa application, capture the ESC key down in Application scope for the whole app, or just in Window scope for some certain windows.

The NSApplicationDelegate is not a subclass of NSResponder, so you can not implement the keyDown: method int app delegate. The NSWindowController is a subclass of NSResponder, you may implement keyDown: method in it, but it will not get invoked when user press the ESC key(with exceptions) and not when user is typing in a text input.

The solution is to use a Event Monitor.

Here’s the sample codes:

 1  @interface MyController : NSWindowController{ 2      id eventMonitor; 3  } 4  @end 5   6  @implementation MyController 7  - (void)windowDidLoad{ 8      NSEvent* (^handler)(NSEvent*) = ^(NSEvent *theEvent) { 9          NSWindow *targetWindow = theEven.window;10          if (targetWindow != self.window) {11              return theEvent;12          }13          14          NSEvent *result = theEvent;15          NSLog(@"event monitor: %@", theEvent);16          if (theEven.keyCode == 53) {17              [self myProcessEscKeyDown];18              result = nil;19          }20  21          return result;22      };23      eventMonitor = [NSEvent addLocalMonitorForEventsMatchingMask:NSKeyDownMask handler:handler];24  }25  26  - (void)windowWillClose:(NSNotification *)notification{27      [NSEvent removeMonitor:eventMonitor];28  }@end

All the stuff is down in a NSWindowController subclass, if you want to implement a key capture in application scope, put these codes in the application delegate, replace windowDidLoad: withapplicationDidFinishLaunching:windowWillClose: with applicationWillTerminate:.

0 0
原创粉丝点击