Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 551
wonderer Avatar asked Jul 12 '09 22:07

wonderer


People also ask

How do I get current mouse position?

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.

How do I find my mouse coordinates on a Mac?

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.

Where is the mouse position in Pyautogui?

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.


2 Answers

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.

like image 75
MarcWan Avatar answered Sep 16 '22 17:09

MarcWan


CGEventRef ourEvent = CGEventCreate(NULL); point = CGEventGetLocation(ourEvent); CFRelease(ourEvent); NSLog(@"Location? x= %f, y = %f", (float)point.x, (float)point.y); 
like image 22
wonderer Avatar answered Sep 16 '22 17:09

wonderer