如何在Mac OS X中获取相对于窗口的光标位置?

时间:2022-09-30 16:49:34

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.

我可以使用[NSEvent mouseLocation]来获取光标的位置,但这会给我屏幕坐标。如何获取光标相对于视图的坐标,当它在其中时?我搜索了Apple文档但找不到答案。

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

如果它有所作为,我将希望不断检索鼠标位置,因为它将在每次帧更新中使用。

3 个解决方案

#1


7  

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

Also make sure you have enabled mouseMoved events:

还要确保已启用mouseMoved事件:

[window setAcceptsMouseMovedEvents:YES];

#2


9  

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)。根据您的窗口布局,这可能等同于视图的坐标。

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.

返回的坐标是窗口坐标,因此如果鼠标留在窗口/窗口下方,则返回负值。如果鼠标位于窗口右侧/上方,则坐标将超出窗口的大小。

#3


7  

NSPoint myPoint = 
    [myView convertPoint:[myWindow convertScreenToBase:[NSEvent mouseLocation]]
                fromView:nil];

#1


7  

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

Also make sure you have enabled mouseMoved events:

还要确保已启用mouseMoved事件:

[window setAcceptsMouseMovedEvents:YES];

#2


9  

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)。根据您的窗口布局,这可能等同于视图的坐标。

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.

返回的坐标是窗口坐标,因此如果鼠标留在窗口/窗口下方,则返回负值。如果鼠标位于窗口右侧/上方,则坐标将超出窗口的大小。

#3


7  

NSPoint myPoint = 
    [myView convertPoint:[myWindow convertScreenToBase:[NSEvent mouseLocation]]
                fromView:nil];