using Moli.Desktop.Diagnostics; using Moli.Desktop.Layout; namespace Moli.Desktop.Interop; /// Attempts to attach wallpaper windows behind desktop icons through Explorer's WorkerW layer. public sealed class WorkerWDesktopLayerStrategy : IDesktopLayerStrategy { private readonly IDiagnosticsService _diagnostics; public WorkerWDesktopLayerStrategy(IDiagnosticsService diagnostics) { _diagnostics = diagnostics; } public string Name => "WorkerW"; public bool IsSupported() => NativeMethods.FindWindow("Progman", null) != IntPtr.Zero; public bool TryAttachDesktopWindow(IntPtr hwnd, RectD bounds, out string? error) { error = null; var workerW = FindWorkerW(); if (workerW == IntPtr.Zero) { error = "WorkerW window was not found."; _diagnostics.Record( DiagnosticSeverity.Warning, DiagnosticCodes.DesktopLayerAttachFailed, "WorkerW desktop layer was not found.", new Dictionary { ["strategy"] = Name }); return false; } if (NativeMethods.SetParent(hwnd, workerW) == IntPtr.Zero) { var lastError = NativeMethods.GetLastError(); if (lastError != 0) { error = $"SetParent failed with {lastError}"; return false; } } if (!NativeMethods.SetWindowPos( hwnd, IntPtr.Zero, (int)bounds.X, (int)bounds.Y, (int)bounds.Width, (int)bounds.Height, NativeMethods.SwpNoZOrder | NativeMethods.SwpNoActivate | NativeMethods.SwpShowWindow)) { error = $"SetWindowPos failed with {NativeMethods.GetLastError()}"; return false; } _diagnostics.Record( DiagnosticSeverity.Info, DiagnosticCodes.DesktopLayerStrategySelected, "Desktop layer strategy selected.", new Dictionary { ["strategy"] = Name }); return true; } private static IntPtr FindWorkerW() { var progman = NativeMethods.FindWindow("Progman", null); if (progman != IntPtr.Zero) { NativeMethods.SendMessageTimeout( progman, 0x052C, IntPtr.Zero, IntPtr.Zero, NativeMethods.SmtoNormal, 1000, out _); } IntPtr workerW = IntPtr.Zero; NativeMethods.EnumWindows((topHandle, _) => { var shellView = NativeMethods.FindWindowEx(topHandle, IntPtr.Zero, "SHELLDLL_DefView", null); if (shellView == IntPtr.Zero) { return true; } workerW = NativeMethods.FindWindowEx(IntPtr.Zero, topHandle, "WorkerW", null); return workerW == IntPtr.Zero; }, IntPtr.Zero); return workerW; } }