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

mk12 picture mk12 · Sep 18, 2011 · Viewed 7.7k times · Source

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.

Answer

user3806037 picture user3806037 · Nov 11, 2014

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.