54 lines
2.1 KiB
C#
54 lines
2.1 KiB
C#
using System.Runtime.InteropServices;
|
|
using CursorLang.Core.Interop;
|
|
|
|
namespace CursorLang.Settings.Interop;
|
|
|
|
/// <summary>
|
|
/// Win32 API for placing the settings window: its own bounds and the work area
|
|
/// of the monitor the window is asked to be put on.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// The bounds are taken from the system rather than from <c>Window.Left/Top/Width/Height</c>:
|
|
/// the window height adapts to its content, and WPF converts those properties using the
|
|
/// monitor DPI, while the monitor work area comes in pixels. Computing the centre in a
|
|
/// single unit is simpler than converting back and forth.
|
|
/// </remarks>
|
|
internal static class WindowPlacementNative
|
|
{
|
|
[DllImport("user32.dll")]
|
|
private static extern bool GetWindowRect(IntPtr hWnd, out PopupWindowNative.Rect lpRect);
|
|
|
|
[DllImport("user32.dll")]
|
|
private static extern IntPtr MonitorFromRect(ref PopupWindowNative.Rect lprc, uint dwFlags);
|
|
|
|
[DllImport("user32.dll")]
|
|
private static extern bool GetMonitorInfo(IntPtr hMonitor, ref MonitorInfo lpmi);
|
|
|
|
[StructLayout(LayoutKind.Sequential)]
|
|
private struct MonitorInfo
|
|
{
|
|
public int cbSize;
|
|
public PopupWindowNative.Rect rcMonitor;
|
|
public PopupWindowNative.Rect rcWork;
|
|
public uint dwFlags;
|
|
}
|
|
|
|
private const uint MONITOR_DEFAULTTONEAREST = 2;
|
|
|
|
/// <summary>The window bounds in screen pixels — including the frame and the title bar.</summary>
|
|
internal static PopupWindowNative.Rect? TryGetBounds(IntPtr hWnd) =>
|
|
GetWindowRect(hWnd, out PopupWindowNative.Rect bounds) ? bounds : null;
|
|
|
|
/// <summary>
|
|
/// The work area — without the taskbar — of the monitor that holds the
|
|
/// rectangle entirely, or at least most of it.
|
|
/// </summary>
|
|
internal static PopupWindowNative.Rect? TryGetWorkAreaNear(PopupWindowNative.Rect rect)
|
|
{
|
|
IntPtr monitor = MonitorFromRect(ref rect, MONITOR_DEFAULTTONEAREST);
|
|
|
|
var info = new MonitorInfo { cbSize = Marshal.SizeOf<MonitorInfo>() };
|
|
return GetMonitorInfo(monitor, ref info) ? info.rcWork : null;
|
|
}
|
|
}
|