From 933903f9a136ac413b89b86116af7014b20d120d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BA=AD=E8=8C=82=20=E5=8F=B6?= <1160210343@qq.com> Date: Sat, 8 Jun 2024 23:49:30 +0800 Subject: [PATCH] Add primary information & nearest monitor function in monitor info class. --- src/WinUIEx/MonitorInfo.cs | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/src/WinUIEx/MonitorInfo.cs b/src/WinUIEx/MonitorInfo.cs index 4068a9f..e475671 100644 --- a/src/WinUIEx/MonitorInfo.cs +++ b/src/WinUIEx/MonitorInfo.cs @@ -4,6 +4,7 @@ using Windows.Foundation; using System.Collections.Generic; using Windows.Win32; +using System; namespace WinUIEx { @@ -32,6 +33,31 @@ public unsafe static IList GetDisplayMonitors() return list; } + /// + /// Gets the display monitor that is nearest to a given window. + /// + /// Window handle + /// The display monitor that is nearest to a given window, or null if no monitor is found. + public unsafe static MonitorInfo? GetNearestDisplayMonitor(IntPtr hwnd) + { + var nearestMonitor = PInvoke.MonitorFromWindow(new(hwnd), MONITOR_FROM_FLAGS.MONITOR_DEFAULTTONEAREST); + MonitorInfo? nearestMonitorInfo = null; + MONITORENUMPROC callback = new MONITORENUMPROC((HMONITOR monitor, HDC deviceContext, RECT* rect, LPARAM data) => + { + if (monitor == nearestMonitor) + { + nearestMonitorInfo = new MonitorInfo(monitor, rect); + return false; + } + return true; + }); + LPARAM data = new LPARAM(); + bool ok = PInvoke.EnumDisplayMonitors(null, null, callback, data); + if (!ok) + Marshal.ThrowExceptionForHR(Marshal.GetLastWin32Error()); + return nearestMonitorInfo; + } + private readonly HMONITOR _monitor; internal unsafe MonitorInfo(HMONITOR monitor, RECT* rect) @@ -69,6 +95,11 @@ internal unsafe MonitorInfo(HMONITOR monitor, RECT* rect) /// public Rect RectWork { get; } + /// + /// Gets if the monitor is the the primary display monitor. + /// + public bool IsPrimary => _monitor == PInvoke.MonitorFromWindow(new(IntPtr.Zero), MONITOR_FROM_FLAGS.MONITOR_DEFAULTTOPRIMARY); + /// public override string ToString() => $"{Name} {RectMonitor.Width}x{RectMonitor.Height}";