Repository navigation
Expand file tree
/
Copy pathDisplayMonitor.cs
More file actions
90 lines (75 loc) · 2.68 KB
/
Copy pathDisplayMonitor.cs
File metadata and controls
90 lines (75 loc) · 2.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
using System.Runtime.InteropServices;
namespace Rounder.Windows;
public sealed record DisplayMonitor(string DeviceName, Rectangle Bounds, bool IsPrimary, double Scale)
{
public static IReadOnlyList<DisplayMonitor> GetAll()
{
var monitors = new List<DisplayMonitor>();
EnumDisplayMonitors(IntPtr.Zero, IntPtr.Zero, (monitor, _, _, _) =>
{
var info = new MonitorInfoEx();
info.Size = Marshal.SizeOf<MonitorInfoEx>();
if (GetMonitorInfo(monitor, ref info))
{
monitors.Add(new DisplayMonitor(
info.DeviceName,
Rectangle.FromLTRB(info.Monitor.Left, info.Monitor.Top, info.Monitor.Right, info.Monitor.Bottom),
(info.Flags & MonitorInfoPrimary) != 0,
GetScaleFactor(monitor)));
}
return true;
}, IntPtr.Zero);
if (monitors.Count > 0)
{
return monitors;
}
return Screen.AllScreens
.Select(screen => new DisplayMonitor(screen.DeviceName, screen.Bounds, screen.Primary, 1.0))
.ToList();
}
private static double GetScaleFactor(IntPtr monitor)
{
try
{
if (GetDpiForMonitor(monitor, MdtEffectiveDpi, out var dpiX, out _) == 0 && dpiX > 0)
{
return dpiX / 96.0;
}
}
catch (DllNotFoundException)
{
}
catch (EntryPointNotFoundException)
{
}
return 1.0;
}
private const int MonitorInfoPrimary = 1;
private const int DeviceNameLength = 32;
private const int MdtEffectiveDpi = 0;
private delegate bool MonitorEnumProc(IntPtr monitor, IntPtr hdc, IntPtr clipRect, IntPtr data);
[StructLayout(LayoutKind.Sequential)]
private struct Rect
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
private struct MonitorInfoEx
{
public int Size;
public Rect Monitor;
public Rect WorkArea;
public int Flags;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = DeviceNameLength)]
public string DeviceName;
}
[DllImport("user32.dll")]
private static extern bool EnumDisplayMonitors(IntPtr hdc, IntPtr clip, MonitorEnumProc callback, IntPtr data);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern bool GetMonitorInfo(IntPtr monitor, ref MonitorInfoEx info);
[DllImport("shcore.dll")]
private static extern int GetDpiForMonitor(IntPtr monitor, int dpiType, out uint dpiX, out uint dpiY);
}