using System.Runtime.InteropServices; namespace CursorLang.Interop; /// /// 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. /// /// /// The bounds are taken from the system rather than from Window.Left/Top/Width/Height: /// 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. /// 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; /// The window bounds in screen pixels — including the frame and the title bar. internal static PopupWindowNative.Rect? TryGetBounds(IntPtr hWnd) => GetWindowRect(hWnd, out PopupWindowNative.Rect bounds) ? bounds : null; /// /// The work area — without the taskbar — of the monitor that holds the /// rectangle entirely, or at least most of it. /// internal static PopupWindowNative.Rect? TryGetWorkAreaNear(PopupWindowNative.Rect rect) { IntPtr monitor = MonitorFromRect(ref rect, MONITOR_DEFAULTTONEAREST); var info = new MonitorInfo { cbSize = Marshal.SizeOf() }; return GetMonitorInfo(monitor, ref info) ? info.rcWork : null; } }