Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 272
Aᴄʜᴇʀᴏɴғᴀɪʟ Avatar asked Apr 03 '18 07:04

Aᴄʜᴇʀᴏɴғᴀɪʟ


1 Answers

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));
like image 76
Aᴄʜᴇʀᴏɴғᴀɪʟ Avatar answered Sep 23 '22 19:09

Aᴄʜᴇʀᴏɴғᴀɪʟ