Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get cursor position relative to window in Mac OS X?

I can use [NSEvent mouseLocation] to get the cursor's location, but this gives me the screen coordinates. How do I get the coordinates of the cursor relative to the view, when it is in it? I searched the Apple documentation and couldn't find an answer.

If it makes a difference I will want to be continually retrieving the mouse position as it will be used in every frame update.

like image 382
mk12 Avatar asked Sep 18 '11 19:09

mk12


2 Answers

For completeness, there is a direct way to get the mouse position in window co-ordinates (using NSWindow). Depending on your window layout, this may be equivalent to the view's co-ordinates.

NSWindow *myWindow;
NSPoint mousePos;
...
mousePos = [myWindow mouseLocationOutsideOfEventStream];

The co-ordinates returned are in window co-ords, so if the mouse is left of/below the window then a negative value is returned. If the mouse is right of/above the window then the co-ordinate will exceed the window's size.

like image 70
user3806037 Avatar answered Sep 30 '22 04:09

user3806037


NSPoint myPoint = 
    [myView convertPoint:[myWindow convertScreenToBase:[NSEvent mouseLocation]]
                fromView:nil];
like image 34
Mats Avatar answered Sep 30 '22 03:09

Mats