我希望我的OSX应用程序坐在后台,等待键盘快捷键开始工作。它应该配置类似于首选项中的咆哮,或者像statusbar中的dropbox一样可访问。
发布于 2011-01-09 16:17:09
看看DeLong在GitHub上的GitHub类。
DDHotKey是一个易于使用的Cocoa类,用于注册应用程序以响应系统密钥事件或“热键”。 全局热键是一个键组合,它总是执行特定的操作,而不管哪个应用程序是最前面的。例如,Mac默认的热键“命令空间”显示Spotlight搜索栏,即使Finder不是最前面的应用程序。
一张慷慨的执照。
发布于 2011-01-09 16:12:28
如果要在“首选项”中访问它,请使用“首选项窗格”模板。如果希望在状态栏中使用,请创建一个正常的应用程序,在LSUIElement中将Info.plist键设置为1,并使用NSStatusItem创建项。
要想在全球范围内捕捉捷径,还需要包括碳框架。使用RegisterEventHotKey
和UnregisterEventHotKey
注册事件。
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
}
https://stackoverflow.com/questions/4639244
复制相似问题