Detect the display of current mouse position (Windows)

Is there any way, to detect the display where the current mouse cursor is?

Example

  • Display0: (x=0, y=0, w=1920, h=1080)
  • Display1: (x=1920, y=0, w=1920, h=1080)
  • MousePos: (x=2000, y=1000)

Should give me Index 1, because the mouse is on Display1.

With the following code, I’am able to get a list of all displays with the MonitorArea:
https://forum.unity3d.com/threads/c-trying-to-get-for-each-display-displays-the-friendlyname-and-vendorsname.398190/

I get the display names: \\.\DISPLAY1, \\.\DISPLAY2, …

With the following code I can get the absolute mouse coords:

	[DllImport("user32.dll")]
	[return: MarshalAs(UnmanagedType.Bool)]
	private static extern bool GetCursorPos(out MousePosition lpMousePosition);

	[StructLayout(LayoutKind.Sequential)]
	public struct MousePosition {
		public int x;
		public int y;

		public override string ToString() {
			return "[" + x + ", " + y + "]";
		}
	}

So I’am able to get the device name of the display by checking the cursor position against all monitor areas.

The problem is, that Unity uses a different display order. Neither with nor without the command line option -multidisplay Unitys display order matches the Windows display order.

The class Displayhave no information about its area (only width, height but no x, y).

I found a solution:

  1. Get absolute mouse coords sx, sy with GetCursorPos
  2. Get relative mouse coords with r = Display.RelativeMouseAt(new Vector3(sx, sy))
  3. Use the z coordinate: displayIndex = (int) r.z

displayIndex is the index of the display in the Display.displays array.