Skip to content

Instantly share code, notes, and snippets.

@cyrilis
Created April 24, 2015 10:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cyrilis/2d5035aeed47acdbbc62 to your computer and use it in GitHub Desktop.
Save cyrilis/2d5035aeed47acdbbc62 to your computer and use it in GitHub Desktop.
Listen and capture Cocoa global shortcut key events, and "eat" them (prevent event trigger)
CGEventRef myCGEventCallback(CGEventTapProxy proxy, CGEventType type,CGEventRef event, void *refcon){
// Paranoid sanity check.
if ((type != kCGEventKeyDown) && (type != kCGEventKeyUp) && (type !=
NX_SYSDEFINED))
return event;
NSEvent *e = [NSEvent eventWithCGEvent:event];
// We're getting a special event
if( ([e type] == NSSystemDefined && [e subtype] == 8) ) {
// do whatever you do with special events
// return NULL to kill the event
// we're getting a normal key event
} else if([e type] == NSKeyDown || [e type] == NSKeyUp) {
// do whatever you do with regular events
// return NULL to kill the event
}
return event;
}
- (void)listenForKeyEvents
{
CFMachPortRef eventTap, eventTapTest;
CGEventMask eventMask;
CFRunLoopSourceRef runLoopSource;
eventMask = ((1 << kCGEventKeyDown) | (1 << kCGEventKeyUp));
// try creating an event tap just for keypresses. if it fails, we need Universal Access.
eventTapTest = CGEventTapCreate(kCGSessionEventTap,kCGHeadInsertEventTap, 0,eventMask, myCGEventCallback, NULL);
if (!eventTapTest) {
NSLog(@"no tap");
NSAlert *alert = [[[NSAlert alloc] init] autorelease];
[alert addButtonWithTitle:@"Quit"];
[alert setMessageText:@"Could not create an event tap."];
[alert setInformativeText:@"Please enable \"access for assistive devices\" in the Universal Access pane of System Preferences."];
[alert setAlertStyle:NSCriticalAlertStyle];
[alert runModal];
[NSApp terminate:self];
return;
}
// disable the test tap
// causes a crash otherwise (infinite loop with the replacement events, probably)
CGEventTapEnable(eventTapTest, false);
// Create an event tap. We are interested in key presses and system defined keys.
eventTap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap, 0, CGEventMaskBit(NX_SYSDEFINED) | eventMask, myCGEventCallback, NULL);
// Create a run loop source.
runLoopSource = CFMachPortCreateRunLoopSource(
kCFAllocatorDefault, eventTap, 0);
// Add to the current run loop.
CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource,
kCFRunLoopCommonModes);
// Enable the event tap.
CGEventTapEnable(eventTap, true);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment