I need to get the mouse position on the screen on a Mac using Xcode. I have some code that supposedly does that but i always returns x and y as 0:
void queryPointer() { NSPoint mouseLoc; mouseLoc = [NSEvent mouseLocation]; //get current mouse position NSLog(@"Mouse location:"); NSLog(@"x = %d", mouseLoc.x); NSLog(@"y = %d", mouseLoc.y); }
What am I doing wrong? How do you get the current position on the screen? Also, ultimately that position (saved in a NSPoint) needs to be copied into a CGPoint to be used with another function so i need to get this either as x,y coordinates or translate this.
To get the current mouse position we are going to trigger a mouse event. In this case we will use 'mousemove' to log the current X and Y coordinates of the mouse to the console.
Answer: A: It does not use an AppleScript, Shell Script or anything else, but if you are just looking to get the coordinates of the mouse on the screen, +command, shift 4+ will give you the coordinates.
To determine the mouse's current position, we use the statement, pyautogui. position(). This function returns a tuple of the position of the mouse's cursor. The first value is the x-coordinate of where the mouse cursor is.
The author's original code does not work because s/he is attempting to print floats out as %d. The correct code would be:
NSPoint mouseLoc = [NSEvent mouseLocation]; //get current mouse position NSLog(@"Mouse location: %f %f", mouseLoc.x, mouseLoc.y);
You don't need to go to Carbon to do this.
CGEventRef ourEvent = CGEventCreate(NULL); point = CGEventGetLocation(ourEvent); CFRelease(ourEvent); NSLog(@"Location? x= %f, y = %f", (float)point.x, (float)point.y);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With