我希望我的OSX应用程序可以在后台等待键盘快捷键触发。 它应该像“Growl”一样在偏好设置中可配置,或者可以在状态栏中像Dropbox一样访问。
- 我需要使用哪种Xcode模板?
- 如何全局捕获键盘快捷键?
(Note: I have kept the HTML tags intact as requested.)
我希望我的OSX应用程序可以在后台等待键盘快捷键触发。 它应该像“Growl”一样在偏好设置中可配置,或者可以在状态栏中像Dropbox一样访问。
请查看Dave DeLong在GitHub上的DDHotKey类。
DDHotKey是一个易于使用的Cocoa类,用于注册应用程序以响应系统键事件或“热键”。
全局热键是一种键组合,无论前面是哪个应用程序,它始终执行特定操作。例如,Mac OS X默认热键“command-space”显示Spotlight搜索栏,即使Finder不是最前面的应用程序。
还有一份开放的许可。
OSStatus HotKeyEventHandlerProc(EventHandlerCallRef inCallRef, EventRef ev, void* inUserData) {
OSStatus err = noErr;
if(GetEventKind(ev) == kEventHotKeyPressed) {
[(id)inUserData handleKeyPress];
} else if(GetEventKind(ev) == kEventHotKeyReleased) {
[(id)inUserData handleKeyRelease];
} else err = eventNotHandledErr;
return err;
}
//EventHotKeyRef hotKey; instance variable
- (void)installEventHandler {
static BOOL installed = NO;
if(installed) return;
installed = YES;
const EventTypeSpec hotKeyEvents[] = {{kEventClassKeyboard,kEventHotKeyPressed},{kEventClassKeyboard,kEventHotKeyReleased}};
InstallApplicationEventHandler(NewEventHandlerUPP(HotKeyEventHandlerProc),GetEventTypeCount(hotKeyEvents),hotKeyEvents,(void*)self,NULL);
}
- (void)registerHotKey {
[self installEventHandler];
UInt32 virtualKeyCode = ?; //The virtual key code for the key
UInt32 modifiers = cmdKey|shiftKey|optionKey|controlKey; //remove the modifiers you don't want
EventHotKeyID eventID = {'abcd','1234'}; //These can be any 4 character codes. It can be used to identify which key was pressed
RegisterEventHotKey(virtualKeyCode,modifiers,eventID,GetApplicationEventTarget(),0,(EventHotKeyRef*)&hotKey);
}
- (void)unregisterHotKey {
if(hotkey) UnregisterEventHotKey(hotKey);
hotKey = 0;
}
- (void)handleHotKeyPress {
//handle key press
}
- (void)handleHotKeyRelease {
//handle key release
}