如何测试鼠标是否在指定的窗口内?

Bry*_*yan 4 macos cocoa

使用Cocoa,如何检查鼠标是否在我的指定窗口内?我有以下代码检测它是否在窗口的范围内,但如果窗口关闭/隐藏但鼠标仍然在该矩形中,它会错误地打印它在里面.如果另一个窗口在它上面,它也会错误地说它在里面,但是鼠标位于我正在它下面测试的窗口区域内.

NSPoint mouse = [NSEvent mouseLocation];

BOOL mouseInside = NSPointInRect(mouse, self.window.frame);

if (!mouseInside) {
    NSLog(@"mouse isn't inside");
} else {
    NSLog(@"mouse is inside");
}
Run Code Online (Sandbox Code Playgroud)

我尝试过这样的事情:

while ((screen = [screenEnum nextObject]) && !NSMouseInRect(mouse, [screen frame], NO));

if (screen != self.window.screen && mouseInside) {
    NSLog(@"mouse is inside.");
}
Run Code Online (Sandbox Code Playgroud)

但它总是打印"鼠标在里面".

有任何想法吗?或者是建立跟踪区域的唯一途径?

Bry*_*yan 7

Freenode上的mikeash指着我 NSWindow's windowNumberAtPoint:

以下代码似乎可以根据需要使用:

if ([NSWindow windowNumberAtPoint:mouse belowWindowWithWindowNumber:0] != self.window.windowNumber) { 
    NSLog(@"mouse outside");
}
Run Code Online (Sandbox Code Playgroud)