一些Mac应用程序,如iTunes和Spotify,可以响应某些苹果键盘上的播放/暂停/下一曲/上一曲按钮。
据推测,它们正在利用某种NSNotification,我该如何做到同样的效果?
一些Mac应用程序,如iTunes和Spotify,可以响应某些苹果键盘上的播放/暂停/下一曲/上一曲按钮。
据推测,它们正在利用某种NSNotification,我该如何做到同样的效果?
我通过子类化NSApplication(并将该类设置为我的目标信息中的应用程序类)来实现这一点,具体如下:
#import <IOKit/hidsystem/ev_keymap.h>
...
- (void)mediaKeyEvent:(int)key state:(BOOL)state
{
switch (key)
{
// Play pressed
case NX_KEYTYPE_PLAY:
if (state == NO)
[(TSAppController *)[self delegate] togglePlayPause:self];
break;
// FF pressed
case NX_KEYTYPE_FAST:
if (state == YES)
[(TSAppController *)[self delegate] seekForward:self];
break;
// RW pressed
case NX_KEYTYPE_REWIND:
if (state == YES)
[(TSAppController *)[self delegate] seekBack:self];
break;
}
}
- (void)sendEvent:(NSEvent *)event
{
// Catch media key events
if ([event type] == NSSystemDefined && [event subtype] == NX_SUBTYPE_AUX_CONTROL_BUTTONS)
{
int keyCode = (([event data1] & 0xFFFF0000) >> 16);
int keyFlags = ([event data1] & 0x0000FFFF);
int keyState = (((keyFlags & 0xFF00) >> 8)) == 0xA;
// Process the media key event and return
[self mediaKeyEvent:keyCode state:keyState];
return;
}
// Continue on to super
[super sendEvent:event];
}
NX_SUBTYPE_AUX_CONTROL_BUTTONS
和NX_KEYUPMASK
/NSKeyUpMask
感兴趣(后者在keyFlags
变量中为0x800
)。 - Peter Hosey