Search code examples
objective-cmacoscocoacursor-position

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.


Solution

  • - (void)mouseMoved:(NSEvent *)event
    {
        NSPoint locationInView = [self convertPoint:[event locationInWindow]
                                           fromView:nil];
    }
    

    Also make sure you have enabled mouseMoved events:

    [window setAcceptsMouseMovedEvents:YES];