Created
May 24, 2012 19:12
-
-
Save jason2506/2783615 to your computer and use it in GitHub Desktop.
Capture all key press events in the system.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (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