bdunagan

Brian Dunagan

October 14 2010
Cocoa Tip: Global Hot Keys

Global hotkeys are a very handy method for letting the user access your application without a mouse or command-tab. Cultured Code’s Things uses it very effectively to quickly type in new tasks via control-option-space. I recently implemented it for Remind Me Later for quickly creating events with a simple key stroke: command-option-R. The application does not have to be in the foreground. It doesn’t even need a window. It just needs to be listening.

Frankly, the hardest part is figuring out the correct keycode. The best place on the Mac seems to be Events.h, in HIToolbox.framework (cd /Developer; find . -name “Events.h”).

// MIT license
// add Carbon.framework

#import <Carbon/Carbon.h>

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
	[self registerHotKeys];
}

- (void)registerHotKeys {
	EventHotKeyRef gMyHotKeyRef;
	EventHotKeyID gMyHotKeyID;
	EventTypeSpec eventType;
	eventType.eventClass=kEventClassKeyboard;
	eventType.eventKind=kEventHotKeyPressed;
	InstallApplicationEventHandler(&MyHotKeyHandler, 1, &eventType, NULL, NULL);
	gMyHotKeyID.signature='rml1';
	gMyHotKeyID.id=1;
	RegisterEventHotKey(kVK_ANSI_R, cmdKey+optionKey, gMyHotKeyID,GetApplicationEventTarget(), 0, &gMyHotKeyRef);
}

OSStatus MyHotKeyHandler(EventHandlerCallRef nextHandler,EventRef theEvent, void *userData) {
	NSLog(@"The hot key was pressed.");
	return noErr;
}
Remind Me Later: Quickly add events to iCal Cocoa Tip: Hot Keys without Key Equivalents
LinkedIn GitHub Email