如何在Objective-C / Cocoa(Mac)中注册全局热键?
例如,我要注册的热键是 Alt - Cmd - D
任何帮助将不胜感激!
答案 0 :(得分:10)
GitHub上有一个方便的Cocoa包装器,用于所需的Carbon函数:JFHotkeyManager。您也可以使用新的(自10.6开始)NSEvent API addGlobalMonitorForEventsMatchingMask:handler:
,但只有在启用辅助设备访问时才会获得关键事件。
答案 1 :(得分:7)
我写了一个包装类,使这更容易......
答案 2 :(得分:4)
您需要使用Carbon框架中的InstallApplicationEventHandler
和RegisterEventHotKey
函数。这个blog post提供了一个非常好的操作方法(这是我在解决这些问题时使用的方法)。
答案 3 :(得分:4)
你去:
#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