Skip to content

Instantly share code, notes, and snippets.

@jason2506
Created May 24, 2012 19:12
Show Gist options
  • Save jason2506/2783615 to your computer and use it in GitHub Desktop.
Save jason2506/2783615 to your computer and use it in GitHub Desktop.
Capture all key press events in the system.
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
CGEventMask eventMask = CGEventMaskBit(kCGEventKeyDown);
CFMachPortRef eventTap = CGEventTapCreate(kCGHIDEventTap,
kCGHeadInsertEventTap,
kCGEventTapOptionDefault,
eventMask,
eventHandler,
NULL);
CFRunLoopSourceRef runLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventTap, 0);
CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopCommonModes);
CGEventTapEnable(eventTap, true);
CFRelease(eventTap);
CFRelease(runLoopSource);
}
CGEventRef eventHandler(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon)
{
NSEvent *sysEvent = [NSEvent eventWithCGEvent:event];
// get the application that trigger the event
NSRunningApplication *activedApp = nil;
NSArray *appList = [[NSWorkspace sharedWorkspace] runningApplications];
for (NSRunningApplication *app in appList)
{
if (app.active)
{
activedApp = app;
break;
}
}
NSLog(@"[%@] %@", [activedApp localizedName], [sysEvent characters]);
return event; // return NULL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment