OSX键盘快捷方式背景应用程序,如何操作?

14

我希望我的OSX应用程序可以在后台等待键盘快捷键触发。 它应该像“Growl”一样在偏好设置中可配置,或者可以在状态栏中像Dropbox一样访问。

  • 我需要使用哪种Xcode模板?
  • 如何全局捕获键盘快捷键?

(Note: I have kept the HTML tags intact as requested.)
2个回答

14

请查看Dave DeLong在GitHub上的DDHotKey类。

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

全局热键是一种键组合,无论前面是哪个应用程序,它始终执行特定操作。例如,Mac OS X默认热键“command-space”显示Spotlight搜索栏,即使Finder不是最前面的应用程序。

还有一份开放的许可。


11
如果您想在偏好设置中访问它,请使用“Preference Pane”模板。如果您想将其放在状态栏中,请创建一个普通应用程序,在Info.plist中将LSUIElement键设置为1,并使用NSStatusItem来创建该项。
要全局捕获快捷键,您还需要包括Carbon框架。使用“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
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接