Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhance MonitorInfo class #175

Closed
wants to merge 3 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions src/WinUIEx/MonitorInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using Windows.Foundation;
using System.Collections.Generic;
using Windows.Win32;
using System;

namespace WinUIEx
{
Expand Down Expand Up @@ -32,6 +33,31 @@ public unsafe static IList<MonitorInfo> GetDisplayMonitors()
return list;
}

/// <summary>
/// Gets the display monitor that is nearest to a given window.
/// </summary>
/// <param name="hwnd">Window handle</param>
/// <returns>The display monitor that is nearest to a given window, or null if no monitor is found.</returns>
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)
Expand Down Expand Up @@ -69,6 +95,11 @@ internal unsafe MonitorInfo(HMONITOR monitor, RECT* rect)
/// </remarks>
public Rect RectWork { get; }

/// <summary>
/// Gets if the monitor is the the primary display monitor.
/// </summary>
public bool IsPrimary => _monitor == PInvoke.MonitorFromWindow(new(IntPtr.Zero), MONITOR_FROM_FLAGS.MONITOR_DEFAULTTOPRIMARY);

/// <inheritdoc />
public override string ToString() => $"{Name} {RectMonitor.Width}x{RectMonitor.Height}";

Expand Down
Loading