views:

2078

answers:

2

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.

thanks!

EDIT:

found the answer:

CGEventRef ourEvent = CGEventCreate(NULL);
point = CGEventGetLocation(ourEvent);
NSLog(@"Location? x= %f, y = %f", (float)point.x, (float)point.y);
+3  A: 
CGEventRef ourEvent = CGEventCreate(NULL);
point = CGEventGetLocation(ourEvent);
NSLog(@"Location? x= %f, y = %f", (float)point.x, (float)point.y);
wonderer
Don't forget to release that CGEventRef!
kperryua
Thanks for the advice!
wonderer
as marcwan has answered, the example in the question doesn't work because of an error with NSLog, the rest is fine.
Steph Thirion
+4  A: 

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;
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.

That's Quartz Event Services, not Carbon, but otherwise you're correct: Cocoa will do this job just fine, without creating a CGEvent object.
Peter Hosey
Whoops, being a 99% Cocoa guy myself, I'm not all that good with the nomenclature of the stuff underneath. Thanks for the clarification :)

related questions