基于WebView2实现的Win11桌面框架,利用插件自定义
chunhualin1
2026-08-14 09d4e2f1a1bc206c80d8d3287d070c70ec7fd63d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
using Moli.Desktop.Configuration;
using Moli.Desktop.Diagnostics;
using Moli.Desktop.Layout;
 
namespace Moli.Desktop.Interop;
 
/// <summary>Attempts to attach desktop surfaces through Explorer's WorkerW or Progman desktop host.</summary>
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, MonitorInfo monitor, RectD bounds, out string? error)
    {
        error = null;
        var scale = monitor.Scale;
        var physicalX = (int)(bounds.X * scale);
        var physicalY = (int)(bounds.Y * scale);
        var physicalW = (int)(bounds.Width * scale);
        var physicalH = (int)(bounds.Height * scale);
 
        var workers = EnumerateWorkerWindows();
        if (workers.Count == 0)
        {
            error = "No WorkerW or Progman desktop host window found.";
            _diagnostics.Record(
                DiagnosticSeverity.Warning,
                DiagnosticCodes.DesktopLayerAttachFailed,
                "No WorkerW or Progman desktop host window found.",
                new Dictionary<string, string> { ["strategy"] = Name });
            return false;
        }
 
        var desktopHost = MatchWorkerWToMonitor(workers, monitor);
        if (desktopHost == IntPtr.Zero)
        {
            error = "No matching WorkerW for target monitor.";
            _diagnostics.Record(
                DiagnosticSeverity.Warning,
                DiagnosticCodes.DesktopLayerAttachFailed,
                "No matching WorkerW for target monitor.",
                new Dictionary<string, string>
                {
                    ["strategy"] = Name,
                    ["monitorId"] = monitor.Id.Value
                });
            return false;
        }
 
        desktopHost = ValidateAndRefreshHandle(desktopHost, monitor, ref workers);
        if (desktopHost == IntPtr.Zero)
        {
            error = "WorkerW handle became invalid and no replacement was found.";
            _diagnostics.Record(
                DiagnosticSeverity.Warning,
                DiagnosticCodes.DesktopLayerAttachFailed,
                "WorkerW handle invalidated and re-enumeration failed.",
                new Dictionary<string, string>
                {
                    ["strategy"] = Name,
                    ["monitorId"] = monitor.Id.Value
                });
            return false;
        }
 
        SetDesktopChildStyle(hwnd);
 
        if (NativeMethods.SetParent(hwnd, desktopHost) == IntPtr.Zero)
        {
            var lastError = NativeMethods.GetLastError();
            if (lastError != 0)
            {
                error = $"SetParent failed with {lastError}";
                RestoreTopLevelStyle(hwnd);
                return false;
            }
        }
 
        NativeMethods.GetWindowRect(desktopHost, out var hostRect);
        var clientX = physicalX - hostRect.Left;
        var clientY = physicalY - hostRect.Top;
 
        if (!NativeMethods.SetWindowPos(
            hwnd,
            IntPtr.Zero,
            clientX,
            clientY,
            physicalW,
            physicalH,
            NativeMethods.SwpNoZOrder | NativeMethods.SwpNoActivate | NativeMethods.SwpFrameChanged | NativeMethods.SwpShowWindow))
        {
            error = $"SetWindowPos failed with {NativeMethods.GetLastError()}";
            NativeMethods.SetParent(hwnd, IntPtr.Zero);
            RestoreTopLevelStyle(hwnd);
            return false;
        }
 
        _diagnostics.Record(
            DiagnosticSeverity.Info,
            DiagnosticCodes.DesktopLayerStrategySelected,
            "Desktop layer strategy selected.",
            new Dictionary<string, string>
            {
                ["strategy"] = Name,
                ["host"] = desktopHost.ToString("X"),
                ["monitorId"] = monitor.Id.Value,
                ["scale"] = scale.ToString("F2")
            });
        return true;
    }
 
    private static IntPtr ValidateAndRefreshHandle(
        IntPtr candidate,
        MonitorInfo monitor,
        ref List<(IntPtr hwnd, NativeMethods.Rect rect)> workers)
    {
        if (NativeMethods.IsWindow(candidate))
        {
            return candidate;
        }
 
        workers.RemoveAll(w => w.hwnd == candidate);
        if (workers.Count == 0)
        {
            workers = EnumerateWorkerWindows();
        }
 
        return MatchWorkerWToMonitor(workers, monitor);
    }
 
    private static List<(IntPtr hwnd, NativeMethods.Rect rect)> EnumerateWorkerWindows()
    {
        var workers = new List<(IntPtr, NativeMethods.Rect)>();
 
        var progman = NativeMethods.FindWindow("Progman", null);
        if (progman != IntPtr.Zero)
        {
            NativeMethods.SendMessageTimeout(
                progman,
                0x052C,
                new IntPtr(0xD),
                IntPtr.Zero,
                NativeMethods.SmtoNormal,
                1000,
                out _);
            NativeMethods.SendMessageTimeout(
                progman,
                0x052C,
                IntPtr.Zero,
                IntPtr.Zero,
                NativeMethods.SmtoNormal,
                1000,
                out _);
        }
 
        NativeMethods.EnumWindows((topHandle, _) =>
        {
            var shellView = NativeMethods.FindWindowEx(topHandle, IntPtr.Zero, "SHELLDLL_DefView", null);
            if (shellView == IntPtr.Zero)
            {
                return true;
            }
 
            var workerW = NativeMethods.FindWindowEx(IntPtr.Zero, topHandle, "WorkerW", null);
            if (workerW != IntPtr.Zero && NativeMethods.IsWindow(workerW) && NativeMethods.GetWindowRect(workerW, out var rect))
            {
                workers.Add((workerW, rect));
            }
 
            return true;
        }, IntPtr.Zero);
 
        if (workers.Count == 0 && progman != IntPtr.Zero && NativeMethods.GetWindowRect(progman, out var progmanRect))
        {
            workers.Add((progman, progmanRect));
        }
 
        return workers;
    }
 
    private static IntPtr MatchWorkerWToMonitor(
        List<(IntPtr hwnd, NativeMethods.Rect rect)> workers,
        MonitorInfo monitor)
    {
        if (workers.Count == 0)
        {
            return IntPtr.Zero;
        }
 
        if (workers.Count == 1)
        {
            return workers[0].hwnd;
        }
 
        var scale = monitor.Scale;
        var monitorLeft = monitor.Bounds.X * scale;
        var monitorTop = monitor.Bounds.Y * scale;
        var monitorRight = (monitor.Bounds.X + monitor.Bounds.Width) * scale;
        var monitorBottom = (monitor.Bounds.Y + monitor.Bounds.Height) * scale;
 
        var bestMatch = workers[0].hwnd;
        var bestOverlap = 0.0;
 
        foreach (var (hwnd, rect) in workers)
        {
            var overlapLeft = Math.Max(monitorLeft, (double)rect.Left);
            var overlapTop = Math.Max(monitorTop, (double)rect.Top);
            var overlapRight = Math.Min(monitorRight, (double)rect.Right);
            var overlapBottom = Math.Min(monitorBottom, (double)rect.Bottom);
            var overlapWidth = Math.Max(0, overlapRight - overlapLeft);
            var overlapHeight = Math.Max(0, overlapBottom - overlapTop);
            var overlapArea = overlapWidth * overlapHeight;
 
            if (overlapArea > bestOverlap)
            {
                bestOverlap = overlapArea;
                bestMatch = hwnd;
            }
        }
 
        return bestMatch;
    }
 
    private static void SetDesktopChildStyle(IntPtr hwnd)
    {
        var current = unchecked((uint)NativeMethods.GetWindowLongPtr(hwnd, NativeMethods.GwlStyle).ToInt64());
        var updated = (current | NativeMethods.WsChild | NativeMethods.WsVisible) & ~NativeMethods.WsPopup;
        NativeMethods.SetWindowLongPtr(hwnd, NativeMethods.GwlStyle, new IntPtr(unchecked((int)updated)));
    }
 
    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)));
    }
}