Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you implement global keyboard hooks in Mac OS X?

I know this can be done for Windows and that XGrabKey can be used for X11, but what about Mac OS X? I want create a class that allows setting shortcut keys that can be invoked even when the application windows are inactive.

like image 325
Jake Petroules Avatar asked May 24 '10 05:05

Jake Petroules


1 Answers

This is not (yet?) supported in Cocoa. You can still use the old Carbon library for this (which is 64 bit compatible), but unfortunately Apple decided to remove all documentation on the subject.

There's a nice blog article here: http://dbachrach.com/blog/2005/11/program-global-hotkeys-in-cocoa-easily/

The article is a bit lengthy for my taste, so here is the short version:

- (id)init {
    self = [super init];
    if (self) {
        EventHotKeyRef  hotKeyRef;
        EventHotKeyID   hotKeyId;
        EventTypeSpec   eventType;

        eventType.eventClass    = kEventClassKeyboard;
        eventType.eventKind     = kEventHotKeyPressed;

        InstallApplicationEventHandler(&mbHotKeyHandler, 1, &eventType, NULL, NULL);

        hotKeyId.signature  = 'hotk';
        hotKeyId.id         = 1337;

        RegisterEventHotKey(kVK_ANSI_C, cmdKey + shiftKey, hotKeyCopyId, GetApplicationEventTarget(), 0, &hotKeyRef);
    }
}

OSStatus mbHotKeyHandler(EventHandlerCallRef nextHandler, EventRef event, void *userData) {
    // Your hotkey was pressed!     
    return noErr;
}

The hotkey is registered with the RegisterEventHotKey(…) call. In this case it registers CMD + Shift + C.

The ANSI keys are defined in HIToolbox/Events.h, so you can look around there for other keys (just press CMD + Shift + O in XCode, and type Events.h to find it).

You have to do a bit more work if you want multiple hotkeys or if you want to call methods from your handler, but that's all in the link near the top of this answer.

I've been looking for a simple answer to this question, so I hope this helps someone else...

like image 83
Bob Vork Avatar answered Sep 22 '22 13:09

Bob Vork