Registration Hotkey

How to register a global hotkey in Objective-C / Cocoa (Mac)?

For example, the hotkey I would like to register would be Alt - Cmd - D

Any help would be appreciated!

+7
source share
4 answers

There is a convenient Cocoa shell for the required Carbon functions on GitHub: JFHotkeyManager . You can also use the new (starting from 10.6) NSEvent addGlobalMonitorForEventsMatchingMask:handler: API, but it only receives key events if access is enabled for auxiliary devices.

+10
source

I wrote a wrapper class to make this a lot easier ...

https://github.com/davedelong/DDHotKey

+7
source

You want to use the InstallApplicationEventHandler and RegisterEventHotKey functions in the Carbon framework. This blog post post gives pretty good practical guidance (this is what I used when I figured out this stuff).

+4
source

here you go:

 #import <Carbon/Carbon.h> EventHandlerUPP hotKeyFunction; pascal OSStatus hotKeyHandler(EventHandlerCallRef nextHandler,EventRef theEvent, void *userData) { FooBar *obj = userData; [obj foo]; return noErr; } @implementation FooBar - (id)init { self = [super init]; if (self) { //handler hotKeyFunction = NewEventHandlerUPP(hotKeyHandler); EventTypeSpec eventType; eventType.eventClass = kEventClassKeyboard; eventType.eventKind = kEventHotKeyReleased; InstallApplicationEventHandler(hotKeyFunction,1,&eventType,self,NULL); //hotkey UInt32 keyCode = 80; //F19 EventHotKeyRef theRef = NULL; EventHotKeyID keyID; keyID.signature = 'FOO '; //arbitrary string keyID.id = 1; RegisterEventHotKey(keyCode,0,keyID,GetApplicationEventTarget(),0,&theRef); } return self; } - (void)foo { } @end 
+4
source

All Articles