OSX键盘快捷键后台应用程序,如何操作

Fab*_*ian 14 macos keyboard-shortcuts backgroundworker

我希望我的OSX应用程序位于后台并等待键盘快捷键才能生效.它应该可以配置为类似于首选项中的Growl,或者可以作为状态栏中的dropbox访问.

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

Abi*_*ern 14

在GitHub上看看Dave DeLong的DDHotKey类.

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

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

慷慨的执照.


ugh*_*fhw 11

如果要在首选项中访问它,请使用"首选项"窗格模板.如果您想在状态栏中创建一个普通应用程序,请在Info.plist中将LSUIElement键设置为1,并使用NSStatusItem创建该项目.

要在全球范围内捕获快捷方式,您还需要包含Carbon框架.使用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
}
Run Code Online (Sandbox Code Playgroud)