开发者

OSX keyboard shortcut background application, how to

开发者 https://www.devze.com 2023-02-03 01:50 出处:网络
I want my OSX application to sit in the background and wait for a keyboard shortcut to go into action. It should be configurable similar to Growl i开发者_如何转开发n the preferences, or accessible as

I want my OSX application to sit in the background and wait for a keyboard shortcut to go into action. It should be configurable similar to Growl i开发者_如何转开发n the preferences, or accessible as dropbox in the statusbar.

  • What kind of xcode template do I have to use?
  • How do I capture keyboard shortcuts globally?


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

精彩评论

暂无评论...
验证码 换一张
取 消