Search code examples
cocoamouseposition

Cocoa: Getting the current mouse position on the screen


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.


Solution

  • CGEventRef ourEvent = CGEventCreate(NULL);
    point = CGEventGetLocation(ourEvent);
    CFRelease(ourEvent);
    NSLog(@"Location? x= %f, y = %f", (float)point.x, (float)point.y);