Media keys hook in Mac OS X
There is no nice (or is it even official?) way of detecting and handling the media keys on the user’s keyboard. One can intercept events with type NSSystemDefined and subtype 8 in -[NSApplication sendEvents:], but this has major problem: any other applications that listen to the media keys will receive these events too. This means for example that if only Spotify is running and you want to pause your music, iTunes will start when you press play/pause. If you have VLC running in the background, it will also start playing.
Apple has solved this problem internally by having their media key using applications cooperate and resign media key controls to the application that was in the foreground most recently. However, there is no way for third party applications to join this cooperation.
I have implemented a workaround that does this using a CGEventTap in the Cocoa class SPMediaKeyTapThe advantage of using an event tap instead of just intercepting the events in -[NSApplication sendEvent:] is that you have the power to throw the event away. This way, we can decide to “own” the media keys and be the only app that listens to them.
This class is smart enough to resign the media key event tap whenever another application that we know will want to use the media keys becomes active, and keeps track of which media key using app was recently started.
If everyone uses this class, and everyone add each other’s bundle ID to that list of whitelisted bundle ID’s, we’ll get nice behavior from all apps. An even better solution would be if Apple provided a way of acquiring the media keys.