Last active
June 19, 2022 18:31
-
-
Save mhamilt/7209c809c03e42a7027e9fe5b18fdfa2 to your computer and use it in GitHub Desktop.
Get the mouse position in macOS with C++
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
#include <ApplicationServices/ApplicationServices.h> | |
#include <iostream> | |
#include <string> | |
///print out location in a nice way to std cout | |
void fancyPrintLocation(CGPoint location); | |
/// This callback will be invoked every time the mouse moves. | |
CGEventRef myCGEventCallback(CGEventTapProxy proxy, CGEventType type, | |
CGEventRef event, void *refcon) | |
{ | |
if (type != kCGEventMouseMoved) | |
{ | |
return event; | |
} | |
CGPoint location = CGEventGetLocation(event); | |
fancyPrintLocation(location); | |
return event; | |
} | |
int main(void) | |
{ | |
CGRect screenBounds = CGDisplayBounds(CGMainDisplayID()); | |
printf( | |
"The main screen is %dx%d\n", | |
(int)screenBounds.size.width, | |
(int)screenBounds.size.height); | |
CFMachPortRef eventTap = CGEventTapCreate( | |
kCGSessionEventTap, | |
kCGHeadInsertEventTap, | |
kCGEventTapOptionDefault, | |
(1 << kCGEventMouseMoved), | |
myCGEventCallback, | |
NULL); | |
if (!eventTap) | |
{ | |
fprintf(stderr, "failed to create event tap\n"); | |
exit(1); | |
} | |
CFRunLoopSourceRef runLoopSource = CFMachPortCreateRunLoopSource( | |
kCFAllocatorDefault, | |
eventTap, | |
0); | |
CFRunLoopAddSource( | |
CFRunLoopGetCurrent(), | |
runLoopSource, | |
kCFRunLoopCommonModes); | |
CGEventTapEnable(eventTap, true); | |
CFRunLoopRun(); | |
exit(0); | |
} | |
void fancyPrintLocation(CGPoint location) | |
{ | |
std::string clearLastLine = ("\33[2K\r("); | |
std::string printOut = | |
clearLastLine + | |
std::to_string((int)(location.x)) + | |
std::string(", ") + | |
std::to_string((int)(location.y)) + | |
std::string(")"); | |
std::cout << printOut << std::flush; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment