基于WebView2实现的Win11桌面框架,利用插件自定义
Moli
2026-05-02 93676d91a7c734cf6b2ace496142e69ccb037775
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
using System.Windows;
using System.Windows.Interop;
using Moli.Desktop.Configuration;
using Moli.Desktop.Diagnostics;
using Moli.Desktop.Layout;
 
namespace Moli.Desktop.Interop;
 
/// <summary>Default Win32 facade for window styles, desktop placement, and monitor discovery.</summary>
public sealed class Win32InteropService : IWin32InteropService
{
    private readonly IReadOnlyList<IDesktopLayerStrategy> _strategies;
    private readonly IDiagnosticsService _diagnostics;
 
    public Win32InteropService(IEnumerable<IDesktopLayerStrategy> strategies, IDiagnosticsService diagnostics)
    {
        _strategies = [.. strategies];
        _diagnostics = diagnostics;
    }
 
    public IntPtr GetWindowHandle(Window window) => new WindowInteropHelper(window).Handle;
 
    public void SetClickThrough(IntPtr hwnd, bool enabled)
    {
        SetStyleFlag(hwnd, NativeMethods.WsExLayered | 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, byte opacity)
    {
        SetStyleFlag(hwnd, NativeMethods.WsExLayered, enabled, "SetLayered");
        if (enabled && !NativeMethods.SetLayeredWindowAttributes(hwnd, 0, opacity, NativeMethods.LwaAlpha))
        {
            RecordWin32Failure("SetLayeredWindowAttributes", hwnd);
        }
    }
 
    public void MoveToDesktopLayer(IntPtr hwnd, DesktopLayerMode mode, MonitorInfo monitor)
    {
        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.TryAttachWallpaperWindow(hwnd, monitor, out var error))
            {
                return;
            }
 
            _diagnostics.Record(
                DiagnosticSeverity.Warning,
                DiagnosticCodes.DesktopLayerAttachFailed,
                "Desktop layer strategy failed.",
                new Dictionary<string, string>
                {
                    ["strategy"] = strategy.Name,
                    ["reason"] = error ?? "Unknown"
                });
        }
    }
 
    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<MonitorInfo> GetMonitors()
    {
        var monitors = new List<MonitorInfo>();
        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<NativeMethods.MonitorInfoEx>(),
                DeviceName = string.Empty
            };
 
            if (!NativeMethods.GetMonitorInfo(hMonitor, ref native))
            {
                return true;
            }
 
            var id = string.IsNullOrWhiteSpace(native.DeviceName)
                ? $"monitor-{monitors.Count + 1}"
                : native.DeviceName;
            monitors.Add(new MonitorInfo
            {
                Id = new MonitorId(native.Flags ? "primary" : id),
                Bounds = ToRectD(native.Monitor),
                WorkArea = ToRectD(native.WorkArea),
                IsPrimary = native.Flags,
                Scale = 1
            });
            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
            }];
    }
 
    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;
        NativeMethods.SetWindowLongPtr(hwnd, NativeMethods.GwlExStyle, new IntPtr(updated));
        var error = NativeMethods.GetLastError();
        if (error != 0)
        {
            _diagnostics.Record(
                DiagnosticSeverity.Warning,
                DiagnosticCodes.Win32InteropFailed,
                $"{operation} failed.",
                new Dictionary<string, string> { ["hwnd"] = hwnd.ToString("X"), ["error"] = error.ToString() });
        }
    }
 
    private void RecordWin32Failure(string operation, IntPtr hwnd)
    {
        _diagnostics.Record(
            DiagnosticSeverity.Warning,
            DiagnosticCodes.Win32InteropFailed,
            $"{operation} failed.",
            new Dictionary<string, string>
            {
                ["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);
    }
}