Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test if the mouse is inside a specified window?

Tags:

macos

cocoa

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?

like image 308
Bryan Avatar asked Jan 17 '23 06:01

Bryan


1 Answers

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");
}
like image 171
Bryan Avatar answered Jan 22 '23 18:01

Bryan