Reputation: 421
With Cocoa, how do I check if the mouse is inside a specified window of mine? I have the following code that detects if it's within the bounds of the window, but it incorrectly prints that it's inside if the window is closed/hidden but the mouse is still in that rectangle. It will also incorrectly say it's inside if another window is on top of it, but the mouse is within the region of the window I'm testing below it.
NSPoint mouse = [NSEvent mouseLocation];
BOOL mouseInside = NSPointInRect(mouse, self.window.frame);
if (!mouseInside) {
NSLog(@"mouse isn't inside");
} else {
NSLog(@"mouse is inside");
}
I've tried something like this:
while ((screen = [screenEnum nextObject]) && !NSMouseInRect(mouse, [screen frame], NO));
if (screen != self.window.screen && mouseInside) {
NSLog(@"mouse is inside.");
}
but it would always print "mouse is inside".
Any ideas? Or is setting up a tracking area the only way?
Upvotes: 4
Views: 1013
Reputation: 421
mikeash on Freenode pointed me to NSWindow's windowNumberAtPoint:
The following code appears to work as needed:
if ([NSWindow windowNumberAtPoint:mouse belowWindowWithWindowNumber:0] != self.window.windowNumber) {
NSLog(@"mouse outside");
}
Upvotes: 9