views:

466

answers:

2

I am fairly new to OSX development, so this may be easy but google has not been helpful.

I am trying to bind an action to the media keys you find on newer Apple keyboards (Play, Pause , etc). It appears that you cannot bind to these keys using the regular hotkey API but it must be possible since iTunes clearly manages. Is there some tricky undocumented API that achieves this? Any help would be much appreciated.

+2  A: 

From my investigations, the operating system is trapping those key events before they are available to other processes. I created a CGEventTap, like so:

int main(int argc, char *argv[]) {
CFMachPortRef      eventTap;
CFRunLoopSourceRef runLoopSource;

eventTap = CGEventTapCreate(kCGHIDEventTap, kCGHeadInsertEventTap, kCGEventTapOptionListenOnly, kCGEventMaskForAllEvents, myCGEventCallback, NULL);

if (!eventTap) {
 NSLog(@"Couldn't create event tap!");
    exit(1);
}

runLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventTap, 0);

CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopCommonModes);

CGEventTapEnable(eventTap, true);

CFRunLoopRun();

CFRelease(eventTap);
CFRelease(runLoopSource);

exit(0);

}

And then the actual event callback is this:

CGEventRef myCGEventCallback(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon) {
    if (type == kCGEventKeyUp) {
     CGKeyCode keycode = CGEventGetIntegerValueField(event, kCGKeyboardEventKeycode);
     NSLog(@"%d", keycode);
    }

    return event;
}

What you see logged to the console is that you get normal log methods for function keys (if you're holding down the "fn" key as well), but when pressing the media keys, brightness, volume, or eject keys, nothing is getting logged.

So from this, it unfortunately appears that there's no way to capture a media key event. However, I would love to be proved wrong.

EDIT: I forgot to point out that for this to work it either needs to run as root, or you need to turn on access for assistive devices in the "Universal Access" pane of System Preferences.

Dave DeLong
This is also the conclusion that I came to, however iTunes is clearly hooking into it SOMEHOW unless there is a hardcoded exception for iTunes somewhere deep in the kernel? I would find that odd...
tryx
+2  A: 

After more extensive googling, this http://www.rogueamoeba.com/utm/2007/09/29/ seems to address the issue. There is no easy solution but if you are developing a real Cocoa app this seems possible at least.

tryx