OSX keyboard shortcut background application, how to

假装没事ソ 提交于 2019-11-28 20:45:03

Have a look at Dave DeLong's DDHotKey class on GitHub.

DDHotKey is an easy-to-use Cocoa class for registering an application to respond to system key events, or "hotkeys".

A global hotkey is a key combination that always executes a specific action, regardless of which app is frontmost. For example, the Mac OS X default hotkey of "command-space" shows the Spotlight search bar, even if Finder is not the frontmost application.

A generous licence as well.

If you want to access it in preferences, use the Preference Pane template. If you want it in the status bar, create a normal application, set the LSUIElement key to 1 in Info.plist, and use NSStatusItem to create the item.

To capture shortcuts globally, you need to include the Carbon framework also. Use RegisterEventHotKey and UnregisterEventHotKey to register for the events.

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
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!