Cocoa: Getting the current mouse position on the screen

wonderer picture wonderer · Jul 13, 2009 · Viewed 28.4k times · Source

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.

Answer

MarcWan picture MarcWan · Dec 9, 2009

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.