基于WebView2实现的Win11桌面框架,利用插件自定义
chunhualin1
2026-08-12 da97410f48a1e94d7e1fe019c69a7c847fe67ddf
src/Moli.Desktop/Windows/WidgetWindow.cs
@@ -13,6 +13,8 @@
using Moli.Desktop.Runtime;
using Moli.Desktop.WebView;
using Brushes = System.Windows.Media.Brushes;
using Color = System.Windows.Media.Color;
using SolidColorBrush = System.Windows.Media.SolidColorBrush;
using Cursors = System.Windows.Input.Cursors;
using HorizontalAlignment = System.Windows.HorizontalAlignment;
using MouseEventArgs = System.Windows.Input.MouseEventArgs;
@@ -24,6 +26,13 @@
public sealed class WidgetWindow : Window
{
    private const double ResizeGripSize = 18;
    /// <summary>
    /// WPF AllowsTransparency uses UpdateLayeredWindow hit-testing against the WPF alpha
    /// bitmap. Fully transparent pixels are skipped even when WS_EX_TRANSPARENT is off, so a
    /// Transparent background over WebView2 (HwndHost) makes the widget look like a sticker.
    /// Alpha=1 keeps hits while remaining visually invisible.
    /// </summary>
    private static readonly SolidColorBrush HitTestBackground = CreateHitTestBackground();
    private readonly PluginDescriptor _plugin;
    private readonly IWebViewHost _webView;
    private readonly IWin32InteropService _interop;
@@ -33,12 +42,15 @@
    private readonly Border _editBorder;
    private readonly Border _resizeGrip;
    private WidgetLayout _layout;
    private MonitorInfo? _monitorInfo;
    private double? _requestedHeight;
    private bool _editMode;
    private bool _safeInputMode;
    private Point? _dragStart;
    private RectD _startBounds;
    private bool _resizing;
    private DisplayLayer? _lastDisplayLayer;
    private bool _desktopLayerAttached;
    public WidgetWindow(
        PluginDescriptor plugin,
@@ -61,12 +73,12 @@
        WindowStyle = WindowStyle.None;
        ResizeMode = ResizeMode.NoResize;
        AllowsTransparency = true;
        Background = Brushes.Transparent;
        Background = HitTestBackground;
        ShowInTaskbar = false;
        Topmost = false;
        SizeToContent = SizeToContent.Manual;
        var root = new Grid { Background = Brushes.Transparent };
        var root = new Grid { Background = HitTestBackground };
        root.Children.Add(webView.View);
        _editBorder = new Border
        {
@@ -148,7 +160,6 @@
            ? height.Value
            : null;
        Height = Math.Max(_layout.Bounds.Height, _requestedHeight ?? _layout.Bounds.Height);
        ApplyWin32Styles();
    }
    public Task SetEditModeAsync(bool enabled, CancellationToken cancellationToken = default)
@@ -160,6 +171,12 @@
    public void SetSafeInputMode(bool enabled)
    {
        _safeInputMode = enabled;
        ApplyWin32Styles();
    }
    public void SetMonitorInfo(MonitorInfo? monitorInfo)
    {
        _monitorInfo = monitorInfo;
        ApplyWin32Styles();
    }
@@ -224,7 +241,27 @@
        var bounds = new RectD(Left, Top, Width, Height);
        _dragStart = null;
        _resizing = false;
        await _commitLayoutAsync(_layout.InstanceId, new WidgetLayoutPatch { Bounds = bounds }, CancellationToken.None);
        var patch = new WidgetLayoutPatch { Bounds = bounds };
        try
        {
            var monitors = _interop.GetMonitors();
            if (monitors.Count > 0)
            {
                var bestMonitor = monitors
                    .Select(m => new { Monitor = m, Overlap = ComputeOverlapArea(bounds, m.Bounds) })
                    .MaxBy(x => x.Overlap);
                if (bestMonitor is not null && bestMonitor.Monitor.Id != _layout.MonitorId)
                {
                    patch = patch with { MonitorId = bestMonitor.Monitor.Id };
                }
            }
        }
        catch
        {
        }
        await _commitLayoutAsync(_layout.InstanceId, patch, CancellationToken.None);
    }
    private void BeginPointerOperation(MouseButtonEventArgs e)
@@ -264,6 +301,20 @@
        DisplayLayer = _layout.DisplayLayer
    };
    private static double ComputeOverlapArea(RectD a, RectD b)
    {
        var overlapX = Math.Max(0, Math.Min(a.Right, b.Right) - Math.Max(a.X, b.X));
        var overlapY = Math.Max(0, Math.Min(a.Bottom, b.Bottom) - Math.Max(a.Y, b.Y));
        return overlapX * overlapY;
    }
    private static SolidColorBrush CreateHitTestBackground()
    {
        var brush = new SolidColorBrush(Color.FromArgb(1, 0, 0, 0));
        brush.Freeze();
        return brush;
    }
    private void ApplyWin32Styles()
    {
        var hwnd = _interop.GetWindowHandle(this);
@@ -275,24 +326,64 @@
        try
        {
            _interop.SetToolWindow(hwnd, true);
            _interop.SetLayered(hwnd, true, ToAlpha(_layout.Opacity));
            _interop.SetLayered(hwnd, true);
            _interop.SetClickThrough(hwnd, !_editMode && !_safeInputMode && _layout.ClickThrough);
            switch (_layout.DisplayLayer)
            var currentLayer = _layout.DisplayLayer;
            var layerChanged = currentLayer != _lastDisplayLayer;
            var needsDesktopAttach = currentLayer == DisplayLayer.Desktop
                && _monitorInfo is not null
                && (!_desktopLayerAttached || layerChanged);
            var needsTopLevelRestore = currentLayer != DisplayLayer.Desktop
                && (layerChanged || _desktopLayerAttached);
            if (!layerChanged && !needsDesktopAttach && !needsTopLevelRestore)
            {
                return;
            }
            var parentChanged = false;
            switch (currentLayer)
            {
                case DisplayLayer.Desktop:
                    Topmost = false;
                    _interop.MoveToDesktopLayer(hwnd, DesktopLayerMode.WorkerW, _layout.Bounds);
                    if (needsDesktopAttach)
                    {
                        _interop.MoveToDesktopLayer(hwnd, DesktopLayerMode.WorkerW, _monitorInfo!, _layout.Bounds);
                        _desktopLayerAttached = true;
                        parentChanged = true;
                    }
                    break;
                case DisplayLayer.GlobalTop:
                    _interop.RestoreTopLevelWindow(hwnd);
                    if (needsTopLevelRestore)
                    {
                        _interop.RestoreTopLevelWindow(hwnd);
                        _desktopLayerAttached = false;
                        parentChanged = true;
                    }
                    Topmost = true;
                    break;
                case DisplayLayer.AppTop:
                case DisplayLayer.Normal:
                default:
                    _interop.RestoreTopLevelWindow(hwnd);
                    if (needsTopLevelRestore)
                    {
                        _interop.RestoreTopLevelWindow(hwnd);
                        _desktopLayerAttached = false;
                        parentChanged = true;
                    }
                    Topmost = false;
                    break;
            }
            _lastDisplayLayer = currentLayer;
            if (parentChanged)
            {
                _ = _webView.NotifyParentWindowPositionChangedAsync();
            }
        }
        catch (Exception ex)
@@ -304,6 +395,4 @@
                new Dictionary<string, string> { ["instanceId"] = _layout.InstanceId.Value, ["exception"] = ex.GetType().Name });
        }
    }
    private static byte ToAlpha(double opacity) => (byte)Math.Round(Math.Clamp(opacity, 0.1, 1.0) * 255);
}