using System.Windows; using System.Windows.Interop; using Moli.Desktop.Configuration; using Moli.Desktop.Diagnostics; using Moli.Desktop.Layout; namespace Moli.Desktop.Interop; /// Default Win32 facade for window styles, desktop placement, and monitor discovery. public sealed class Win32InteropService : IWin32InteropService { private readonly IReadOnlyList _strategies; private readonly IDiagnosticsService _diagnostics; public Win32InteropService(IEnumerable strategies, IDiagnosticsService diagnostics) { _strategies = [.. strategies]; _diagnostics = diagnostics; } public IntPtr GetWindowHandle(Window window) => new WindowInteropHelper(window).Handle; public void SetClickThrough(IntPtr hwnd, bool enabled) { // Only toggle WS_EX_TRANSPARENT. WS_EX_LAYERED is owned by SetLayered / WPF // AllowsTransparency; clearing it here would break per-pixel transparency. SetStyleFlag(hwnd, NativeMethods.WsExTransparent, enabled, "SetClickThrough"); } public void SetToolWindow(IntPtr hwnd, bool enabled) { SetStyleFlag(hwnd, NativeMethods.WsExToolWindow, enabled, "SetToolWindow"); } public void SetNoActivate(IntPtr hwnd, bool enabled) { SetStyleFlag(hwnd, NativeMethods.WsExNoActivate, enabled, "SetNoActivate"); } public void SetLayered(IntPtr hwnd, bool enabled) { // Only manage the WS_EX_LAYERED style bit. Never call SetLayeredWindowAttributes here: // it switches the window from WPF AllowsTransparency per-pixel alpha (UpdateLayeredWindow) // to constant-alpha mode, in which transparent pixels composite as opaque black. // Global opacity is handled by Window.Opacity instead. SetStyleFlag(hwnd, NativeMethods.WsExLayered, enabled, "SetLayered"); } public void MoveToDesktopLayer(IntPtr hwnd, DesktopLayerMode mode, MonitorInfo monitor, RectD bounds) { var candidates = mode == DesktopLayerMode.WorkerW ? _strategies.OrderBy(strategy => strategy is WorkerWDesktopLayerStrategy ? 0 : 1) : _strategies.OrderBy(strategy => strategy is BottomDesktopLayerStrategy ? 0 : 1); foreach (var strategy in candidates) { if (!strategy.IsSupported()) { continue; } if (strategy.TryAttachDesktopWindow(hwnd, monitor, bounds, out var error)) { return; } _diagnostics.Record( DiagnosticSeverity.Warning, DiagnosticCodes.DesktopLayerAttachFailed, "Desktop layer strategy failed.", new Dictionary { ["strategy"] = strategy.Name, ["reason"] = error ?? "Unknown" }); } } public void RestoreTopLevelWindow(IntPtr hwnd) { RestoreTopLevelStyle(hwnd); NativeMethods.SetParent(hwnd, IntPtr.Zero); var error = NativeMethods.GetLastError(); if (error != 0) { _diagnostics.Record( DiagnosticSeverity.Warning, DiagnosticCodes.Win32InteropFailed, "RestoreTopLevelWindow failed.", new Dictionary { ["hwnd"] = hwnd.ToString("X"), ["error"] = error.ToString() }); } if (!NativeMethods.SetWindowPos( hwnd, IntPtr.Zero, 0, 0, 0, 0, NativeMethods.SwpNoMove | NativeMethods.SwpNoSize | NativeMethods.SwpNoZOrder | NativeMethods.SwpNoActivate | NativeMethods.SwpFrameChanged)) { RecordWin32Failure("RestoreTopLevelWindow.SetWindowPos", hwnd); } } public void SetBottomMost(IntPtr hwnd) { if (!NativeMethods.SetWindowPos( hwnd, NativeMethods.HwndBottom, 0, 0, 0, 0, NativeMethods.SwpNoMove | NativeMethods.SwpNoSize | NativeMethods.SwpNoActivate)) { RecordWin32Failure("SetBottomMost", hwnd); } } public IReadOnlyList GetMonitors() { var monitors = new List(); NativeMethods.EnumDisplayMonitors(IntPtr.Zero, IntPtr.Zero, ( IntPtr hMonitor, IntPtr hdcMonitor, ref NativeMethods.Rect monitorRect, IntPtr data) => { var native = new NativeMethods.MonitorInfoEx { Size = System.Runtime.InteropServices.Marshal.SizeOf(), DeviceName = string.Empty }; if (!NativeMethods.GetMonitorInfo(hMonitor, ref native)) { return true; } var scale = 1.0; var hr = NativeMethods.GetDpiForMonitor(hMonitor, NativeMethods.MdtEffectiveDpi, out var dpiX, out _); if (hr == 0 && dpiX > 0) { scale = dpiX / 96.0; } var physicalBounds = ToRectD(native.Monitor); var physicalWorkArea = ToRectD(native.WorkArea); var dipBounds = new RectD( physicalBounds.X / scale, physicalBounds.Y / scale, physicalBounds.Width / scale, physicalBounds.Height / scale); var dipWorkArea = new RectD( physicalWorkArea.X / scale, physicalWorkArea.Y / scale, physicalWorkArea.Width / scale, physicalWorkArea.Height / scale); var deviceName = string.IsNullOrWhiteSpace(native.DeviceName) ? $"monitor-{monitors.Count + 1}" : native.DeviceName; monitors.Add(new MonitorInfo { Id = new MonitorId(deviceName), Bounds = dipBounds, WorkArea = dipWorkArea, IsPrimary = native.Flags, Scale = scale }); return true; }, IntPtr.Zero); return monitors.Count > 0 ? monitors : [new MonitorInfo { Id = new MonitorId("primary"), Bounds = new RectD(0, 0, SystemParameters.PrimaryScreenWidth, SystemParameters.PrimaryScreenHeight), WorkArea = new RectD(0, 0, SystemParameters.WorkArea.Width, SystemParameters.WorkArea.Height), IsPrimary = true, Scale = 1 }]; } private void SetStyleFlag(IntPtr hwnd, int flag, bool enabled, string operation) { var current = NativeMethods.GetWindowLongPtr(hwnd, NativeMethods.GwlExStyle).ToInt64(); var styleFlag = unchecked((uint)flag); var currentStyle = unchecked((uint)current); var updated = enabled ? currentStyle | styleFlag : currentStyle & ~styleFlag; if (updated == currentStyle) { return; } NativeMethods.SetWindowLongPtr(hwnd, NativeMethods.GwlExStyle, new IntPtr(unchecked((int)updated))); // Extended-style changes (especially WS_EX_TRANSPARENT) do not reliably update hit-testing // until the frame is refreshed. Without this, clearing click-through in edit/safe-input // mode can leave the window visually present but permanently unclickable. if (!NativeMethods.SetWindowPos( hwnd, IntPtr.Zero, 0, 0, 0, 0, NativeMethods.SwpNoMove | NativeMethods.SwpNoSize | NativeMethods.SwpNoZOrder | NativeMethods.SwpNoActivate | NativeMethods.SwpFrameChanged)) { RecordWin32Failure($"{operation}.SetWindowPos", hwnd); } } private void RecordWin32Failure(string operation, IntPtr hwnd) { _diagnostics.Record( DiagnosticSeverity.Warning, DiagnosticCodes.Win32InteropFailed, $"{operation} failed.", new Dictionary { ["hwnd"] = hwnd.ToString("X"), ["error"] = NativeMethods.GetLastError().ToString() }); } private static RectD ToRectD(NativeMethods.Rect rect) { return new RectD(rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top); } private static void RestoreTopLevelStyle(IntPtr hwnd) { var current = unchecked((uint)NativeMethods.GetWindowLongPtr(hwnd, NativeMethods.GwlStyle).ToInt64()); var updated = (current | NativeMethods.WsPopup | NativeMethods.WsVisible) & ~NativeMethods.WsChild; NativeMethods.SetWindowLongPtr(hwnd, NativeMethods.GwlStyle, new IntPtr(unchecked((int)updated))); } }