Skip to content

Instantly share code, notes, and snippets.

@kylemcdonald
Last active December 1, 2016 20:16
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 kylemcdonald/3f4abf55e718f6e80fd2335c5ac077cc to your computer and use it in GitHub Desktop.
Save kylemcdonald/3f4abf55e718f6e80fd2335c5ac077cc to your computer and use it in GitHub Desktop.
Trying to constrain mouse movement in OS X (doesn't work).
// gcc -Wall -o constrain-event constrain-event.cpp -framework ApplicationServices
#include <ApplicationServices/ApplicationServices.h>
int leftBound;
int topBound;
int rightBound;
int bottomBound;
CGEventRef myCGEventCallback(CGEventTapProxy proxy, CGEventType type,
CGEventRef event, void *refcon) {
CGPoint location = CGEventGetLocation(event);
CGFloat x = location.x, y = location.y;
if(x < leftBound || x > rightBound || y < topBound || y > bottomBound) {
if(x < leftBound) x = leftBound;
if(x > rightBound) x = rightBound;
if(y < topBound) y = topBound;
if(y > bottomBound) y = bottomBound;
CGEventSetLocation(event, CGPointMake(x, y));
}
return event;
}
int main(int argc, const char * argv[]) {
CFMachPortRef eventTap;
CGEventMask eventMask;
CFRunLoopSourceRef runLoopSource;
if(argc != 5) {
printf("Usage: constrain left top right bottom\n");
return 0;
}
leftBound = strtol(argv[1], NULL, 10);
topBound = strtol(argv[2], NULL, 10);
rightBound = strtol(argv[3], NULL, 10);
bottomBound = strtol(argv[4], NULL, 10);
eventMask = (1 << kCGEventMouseMoved);
eventTap = CGEventTapCreate(kCGHIDEventTap, kCGHeadInsertEventTap,
0, eventMask, myCGEventCallback, NULL);
if (!eventTap) {
fprintf(stderr, "failed to create event tap\n");
exit(1);
}
runLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventTap, 0);
CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopCommonModes);
CGEventTapEnable(eventTap, true);
CFRunLoopRun();
CFRelease(runLoopSource);
exit(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment