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

3

7

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.

Kosse answered 18/9, 2011 at 19:39 Comment(0)
L
7
- (void)mouseMoved:(NSEvent *)event
{
    NSPoint locationInView = [self convertPoint:[event locationInWindow]
                                       fromView:nil];
}

Also make sure you have enabled mouseMoved events:

[window setAcceptsMouseMovedEvents:YES];
Leadership answered 18/9, 2011 at 19:50 Comment(1)
theEvent should be event, I think.Poirier
H
12

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.

Headpiece answered 10/11, 2014 at 23:21 Comment(0)
M
8
NSPoint myPoint = 
    [myView convertPoint:[myWindow convertScreenToBase:[NSEvent mouseLocation]]
                fromView:nil];
Migraine answered 18/9, 2011 at 19:48 Comment(1)
convertScreenToBase is deprecatedEclampsia
L
7
- (void)mouseMoved:(NSEvent *)event
{
    NSPoint locationInView = [self convertPoint:[event locationInWindow]
                                       fromView:nil];
}

Also make sure you have enabled mouseMoved events:

[window setAcceptsMouseMovedEvents:YES];
Leadership answered 18/9, 2011 at 19:50 Comment(1)
theEvent should be event, I think.Poirier

© 2022 - 2024 — McMap. All rights reserved.