Registering global hot keys with Cocoa and Objective-C
Objective-C posted almost 4 years ago by christian
In your application’s controller add the following:
1 - (void)awakeFromNib 2 { 3 [self registerHotKeys]; 4 }
And the following code which registers the hot keys:
1 -(void)registerHotKeys 2 { 3 EventHotKeyRef gMyHotKeyRef; 4 EventHotKeyID gMyHotKeyID; 5 EventTypeSpec eventType; 6 eventType.eventClass=kEventClassKeyboard; 7 eventType.eventKind=kEventHotKeyPressed; 8 9 InstallApplicationEventHandler(&OnHotKeyEvent, 1, &eventType, (void *)self, NULL); 10 11 gMyHotKeyID.signature='htk1'; 12 gMyHotKeyID.id=1; 13 RegisterEventHotKey(20, cmdKey+optionKey, gMyHotKeyID, GetApplicationEventTarget(), 0, &gMyHotKeyRef); 14 15 gMyHotKeyID.signature='htk2'; 16 gMyHotKeyID.id=2; 17 RegisterEventHotKey(21, cmdKey+optionKey, gMyHotKeyID, GetApplicationEventTarget(), 0, &gMyHotKeyRef); 18 19 gMyHotKeyID.signature='htk3'; 20 gMyHotKeyID.id=3; 21 RegisterEventHotKey(23, cmdKey+optionKey, gMyHotKeyID, GetApplicationEventTarget(), 0, &gMyHotKeyRef); 22 } 23 24 OSStatus OnHotKeyEvent(EventHandlerCallRef nextHandler,EventRef theEvent,void *userData) 25 { 26 EventHotKeyID hkCom; 27 28 GetEventParameter(theEvent, kEventParamDirectObject, typeEventHotKeyID, NULL, sizeof(hkCom), NULL, &hkCom); 29 AppController *controller = (AppController *)userData; 30 31 int l = hkCom.id; 32 33 switch (l) { 34 case 1: 35 NSLog(@"Capture area"); 36 [ScreenCapture captureArea:controller]; 37 break; 38 case 2: 39 NSLog(@"Capture screen"); 40 [ScreenCapture captureScreen:controller]; 41 break; 42 case 3: 43 NSLog(@"Capture window"); 44 [ScreenCapture captureWindow:controller]; 45 break; 46 } 47 48 return noErr; 49 }
The code used in this snippet was inspired by this blog post http://dbachrach.com/blog/2005/11/28/program-global-hotkeys-in-cocoa-easily/
Alternatives
If you need a more complete solution you can use one of these open-source alternatives:
Showing the application window
Usually you want to show the application window when the hot key is pressed. This can be done as explained in this snippet
