Incorrect location using [NSEvent mouseLocation]

I am making an iphone iphone mouse controller app for Mac: the iPhone app sends coordinate values ​​to a Mac, which then process the mouse location value.

To get the current mouse location on a Mac, the receiver calls [NSEvent mouseLocation].

The value for x is always correct, but the value for y is incorrect.

I used a while loop to handle this event.

while (1) { mouseLoc = [NSEvent mouseLocation]; while ((msgLength = recv(clientSocket, buffer, sizeof(buffer), 0)) != 0) { CGPoint temp; temp.x = mouseLoc.x; temp.y = mouseLoc.y; // wrong value ........ 

The y value in each cycle period is different. For example, y is 400 in the first cycle, y is 500 in the next cycle; then y again 400 in the next loop.

The mouse pointer moves up and down continuously, and the sum of two different y values ​​is always 900. (I think because the screen resolution is 1440 * 900.)

I don’t know why this is happening, what to do and how to debug it.

+4
source share
3 answers

Here you can get the correct value of Y:

 while (1) { mouseLoc = [NSEvent mouseLocation]; NSRect screenRect = [[NSScreen mainScreen] frame]; NSInteger height = screenRect.size.height; while ((msgLength = recv(clientSocket, buffer, sizeof(buffer), 0)) != 0) { CGPoint temp; temp.x = mouseLoc.x; temp.y = height - mouseLoc.y; // wrong value ........ 

Basically, I grabbed the screen height:

 NSRect screenRect = [[NSScreen mainScreen] frame]; NSInteger height = screenRect.size.height; 

Then I take the screen height and subtract the Y coordinate of mouseLocation from it, because mouseLocation returns the coordinates from below / left, this will give you the Y coordinate from above.

 temp.y = height - mouseLoc.y; // right value 

This works in my application, which controls the position of the mouse.

+4
source

I don’t know why this would change without seeing more of your code, but there is a good chance that this has something to do with mouseLoc = [NSEvent mouseLocation]; returns the point whose beginning is in the lower left corner instead of the upper left where it usually will be.

+2
source

Get the code for the right position:

 CGPoint mousePoint = CGPointMake([NSEvent mouseLocation].x, [NSScreen mainScreen].frame.size.height - [NSEvent mouseLocation].y); 
+1
source

Source: https://habr.com/ru/post/1382144/


All Articles