Find which monitor or screen contains mouse pointer - swift, macos
Asked Answered
S

1

10

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?

Suppurate answered 3/4, 2018 at 7:25 Comment(0)
S
20

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.

Swift 4

func getScreenWithMouse() -> NSScreen? {
  let mouseLocation = NSEvent.mouseLocation
  let screens = NSScreen.screens
  let screenWithMouse = (screens.first { NSMouseInRect(mouseLocation, $0.frame, false) })

  return screenWithMouse
}

Objective C

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));
Suppurate answered 3/4, 2018 at 7:25 Comment(2)
@Moritz it sure does compile! I'm already using it :) Are you sure you're using Swift 4? (found a typo in it)Bacchus
Ah, yeah, sorry, I was using Swift 3. Indeed it works with Swift 4. :)Lama

© 2022 - 2024 — McMap. All rights reserved.