[英]How to get cursor position relative to window in Mac OS X?
我可以使用[NSEvent mouseLocation]
来获取光标的位置,但这会给我屏幕坐标。 如何获取光标相对于视图的坐标(当它在其中时)? 我搜索了Apple文档但找不到答案。
如果它有所不同,我会希望不断检索鼠标位置,因为它将在每次帧更新中使用。
为了完整起见,有一种直接的方法可以在窗口坐标中获得鼠标位置(使用NSWindow)。 根据您的窗口布局,这可能等同于视图的坐标。
NSWindow *myWindow;
NSPoint mousePos;
...
mousePos = [myWindow mouseLocationOutsideOfEventStream];
返回的坐标是窗口坐标,因此如果鼠标留在窗口/窗口下方,则返回负值。 如果鼠标位于窗口右侧/上方,则坐标将超出窗口的大小。
NSPoint myPoint =
[myView convertPoint:[myWindow convertScreenToBase:[NSEvent mouseLocation]]
fromView:nil];
- (void)mouseMoved:(NSEvent *)event
{
NSPoint locationInView = [self convertPoint:[event locationInWindow]
fromView:nil];
}
还要确保已启用mouseMoved事件:
[window setAcceptsMouseMovedEvents:YES];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.