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.
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);
Beware mixing the NS environment with the CG environment. If you get the mouse location with the NS mouseLocation method then use CGWarpMouseCursorPosition(cgPoint) you will not be sent to the point on the screen you expected. The problem results from CG using top left as (0,0) while NS uses bottom left as (0,0).
The answer to this question in Swift
let currentMouseLocation = NSEvent.mouseLocation()
let xPosition = currentMouseLocation.x
let yPosition = currentMouseLocation.y
NSLog(@"%@", NSStringFromPoint(point));
NSLog is true;