Skip to content

Instantly share code, notes, and snippets.

@mlabbe
Created January 8, 2025 20:06
Show Gist options
  • Save mlabbe/95639ee8dd3584e73dd0a11d1af1d600 to your computer and use it in GitHub Desktop.
Save mlabbe/95639ee8dd3584e73dd0a11d1af1d600 to your computer and use it in GitHub Desktop.
#import <Cocoa/Cocoa.h>
#import <ApplicationServices/ApplicationServices.h>
CGEventTimestamp lastTimestamp = 0;
CGEventRef eventTapCallback(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon) {
if (type == kCGEventMouseMoved) {
CGPoint location = CGEventGetLocation(event);
NSLog(@"Mouse moved to: x = %.2f, y = %.2f", location.x, location.y);
CGEventTimestamp currentTimestamp = CGEventGetTimestamp(event);
if (lastTimestamp != 0) {
// Calculate time delta in milliseconds
double timeDelta = (currentTimestamp - lastTimestamp) / 1.0e6; // Convert nanoseconds to milliseconds
NSLog(@"Time delta: %.3f ms | Mouse moved to: x = %.2f, y = %.2f", timeDelta, location.x, location.y);
} else {
NSLog(@"Mouse moved to: x = %.2f, y = %.2f", location.x, location.y);
}
lastTimestamp = currentTimestamp;
}
return event;
}
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSLog(@"Starting mouse move logger...");
CGEventMask eventMask = CGEventMaskBit(kCGEventMouseMoved);
CFMachPortRef eventTap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap, 0, eventMask, eventTapCallback, NULL);
if (!eventTap) {
NSLog(@"Failed to create event tap.");
return 1;
}
CFRunLoopSourceRef runLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventTap, 0);
CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopCommonModes);
CGEventTapEnable(eventTap, true);
[[NSRunLoop currentRunLoop] run];
}
return 0;
}
@mlabbe
Copy link
Author

mlabbe commented Jan 14, 2025

Build with

clang -framework Foundation -framework CoreGraphics mouse.m

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment