2011-01-09 71 views
13

我希望我的OSX应用程序坐在后台并等待键盘快捷键进入操作状态。它应该可以在首选项中与Growl类似配置,或者可以在状态栏中以Dropbox的形式访问。OSX键盘快捷键后台应用程序,如何

  • 我必须使用什么样的xcode模板?
  • 如何在全球捕获键盘快捷键?

回答

11

如果您想在首选项中访问它,请使用首选面板模板。如果你想在状态栏中创建一个普通的应用程序,请在Info.plist中将LSUIElement键设置为1,然后使用NSStatusItem创建该项目。

要捕捉全局快捷方式,还需要包括碳框架。使用RegisterEventHotKeyUnregisterEventHotKey注册事件。

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 
} 
13

看看Dave DeLong在GitHub上的DDHotKey类。

DDHotKey是一个易于使用的Cocoa类,用于注册应用程序以响应系统键事件或“热键”。

全局热键是始终执行特定操作的关键组合,无论哪个应用程序位于最前面。例如,即使Finder不是最前面的应用程序,Mac OS X的默认热键“命令空间”也会显示Spotlight搜索栏。

一个慷慨的许可证。

+3

+1好的回答:) – 2011-04-26 03:02:48