I would like to find out which monitor the mouse is on so I can create a window on that monitor.
This is different to which is the main screen, because NSScreen.main
returns whichever screen has the active window inside of it (an easy way to tell is which monitor's menubar is opaque, the others will be dimmed slightly).
From what I can tell there's no direct way to get this?
Answering my own question since I found the answer - this might be helpful to someone else.
It's not too difficult to find which screen/monitor the mouse is on, but you do have to iterate through each screen in order to do so.
func getScreenWithMouse() -> NSScreen? {
let mouseLocation = NSEvent.mouseLocation
let screens = NSScreen.screens
let screenWithMouse = (screens.first { NSMouseInRect(mouseLocation, $0.frame, false) })
return screenWithMouse
}
A similar way to get the same result in Objective-C would be:
NSPoint mouseLoc = [NSEvent mouseLocation];
NSEnumerator *screenEnum = [[NSScreen screens] objectEnumerator];
NSScreen screen;
while ((screen = [screenEnum nextObject]) && !NSMouseInRect(mouseLoc,
[screen frame], NO));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With