How would I register a global hotkey in Objective-C/Cocoa (Mac) ?
For example, the hotkey I'd like to register would be Alt - Cmd - D
Any help would be appreciated!
How would I register a global hotkey in Objective-C/Cocoa (Mac) ?
For example, the hotkey I'd like to register would be Alt - Cmd - D
Any help would be appreciated!
There's a convenient Cocoa wrapper for the required Carbon functions on GitHub: JFHotkeyManager. You could also use the new (since 10.6) NSEvent API addGlobalMonitorForEventsMatchingMask:handler:, but it only gets key events if access for assistive devices is enabled.
I wrote a wrapper class to make this a heck of a lot easier...
here you go:
#import <Carbon/Carbon.h>
EventHandlerUPP hotKeyFunction;
pascal OSStatus hotKeyHandler(EventHandlerCallRef nextHandler,EventRef theEvent, void *userData)
{
FooBar *obj = userData;
[obj foo];
return noErr;
}
@implementation FooBar
- (id)init
{
self = [super init];
if (self) {
//handler
hotKeyFunction = NewEventHandlerUPP(hotKeyHandler);
EventTypeSpec eventType;
eventType.eventClass = kEventClassKeyboard;
eventType.eventKind = kEventHotKeyReleased;
InstallApplicationEventHandler(hotKeyFunction,1,&eventType,self,NULL);
//hotkey
UInt32 keyCode = 80; //F19
EventHotKeyRef theRef = NULL;
EventHotKeyID keyID;
keyID.signature = 'FOO '; //arbitrary string
keyID.id = 1;
RegisterEventHotKey(keyCode,0,keyID,GetApplicationEventTarget(),0,&theRef);
}
return self;
}
- (void)foo
{
}
@end