objective-ccocoansevent

Register a global hotkey without support for assistive devices enabled


Using this code, I may register a global event handler:

[NSEvent addGlobalMonitorForEventsMatchingMask: NSKeyDownMask 
                                       handler: ^(NSEvent *incomingEvent) {

           NSString *chars = [[incomingEvent characters] lowercaseString];
           unichar character = [chars characterAtIndex:0];    

           // do something useful
           NSLog(@"keydown globally! Which key? This key: %c", character);

        }];

Unfortunately, events get passed along to this monitor, if support for assistive devices is enabled. Without assistive devices being enabled, no events get passed along.

Form the documentation:

Key-related events may only be monitored if accessibility is enabled or if your 
application is trusted for accessibility access (see AXIsProcessTrusted).

I wonder, if another method exists, which passes along events without forcing the user to enable specific features of OS X.

While I didn't find a solution in Apple's docs, a solution must exist. E.g. the MAS-downloaded version of Alfred allows to define a hotkey.

Interestingly, Alfred's preferences only shows special keys and points out, that certain special key combinations may not work.

Since I basically want to show / hide a 'global' non-activating panel, I probably should simply prepare a system service. Should I?


Solution

  • You could try creating a Quartz Event Tap, with kCGSessionEventTap as the location.

    Quartz Event Services Reference
    Sample code from Mac OS X Internals