On Mac OS X 10.6 and later, you can use the + addGlobalMonitorForEventsMatchingMask: handler: and + addLocalMonitorForEventsMatchingMask: handler methods: defined from the NSEvent class. Event monitoring reports the following information:
Local and global event monitors are mutually exclusive. For example, the global monitor does not track the event flow of the application in which it is installed. In the local event monitor, only the application event flow is observed. To track events from all applications, including the βcurrentβ application, you must install both event monitors.
The code shown on this page is for the local event monitor, but the code for the global event monitor is the same; what changes cause the NSEvent method.
_eventMonitor = [NSEvent addLocalMonitorForEventsMatchingMask: (NSLeftMouseDownMask | NSRightMouseDownMask | NSOtherMouseDownMask | NSKeyDownMask) handler:^(NSEvent *incomingEvent) { NSEvent *result = incomingEvent; NSWindow *targetWindowForEvent = [incomingEvent window]; if (targetWindowForEvent != _window) { [self _closeAndSendAction:NO]; } else if ([incomingEvent type] == NSKeyDown) { if ([incomingEvent keyCode] == 53) {
Once the monitor is no longer needed, you will remove it using the following code:
[NSEvent removeMonitor:_eventMonitor]
source share