基于WebView2实现的Win11桌面框架,利用插件自定义
chunhualin1
2026-08-12 574a6a769115034f37bdecf3284545d74843816a
添加显示器切换兼容处理
2个文件已添加
18个文件已修改
1465 ■■■■■ 已修改文件
docs/solution/multi-monitor-display-bug-analysis.md 734 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
scripts/publish-to-apps.ps1 2 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop.Tests/Interop/FakeWin32InteropService.cs 17 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop.Tests/Interop/Win32InteropContractTests.cs 15 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop.Tests/Runtime/DesktopRuntimeCoordinatorTests.cs 9 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Host/DesktopHostBuilder.cs 1 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Interop/BottomDesktopLayerStrategy.cs 17 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Interop/DisplayChangeMonitor.cs 113 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Interop/IDesktopLayerStrategy.cs 3 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Interop/IWin32InteropService.cs 5 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Interop/NativeMethods.cs 21 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Interop/Win32InteropService.cs 54 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Interop/WorkerWDesktopLayerStrategy.cs 157 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Layout/LayoutManager.cs 75 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Runtime/DesktopRuntimeCoordinator.cs 29 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Runtime/IDesktopRuntime.cs 1 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Runtime/IRuntimeSurfaceController.cs 3 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Windows/RuntimeSurfaceController.cs 153 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Windows/WallpaperWindow.cs 10 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Windows/WidgetWindow.cs 46 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
docs/solution/multi-monitor-display-bug-analysis.md
New file
@@ -0,0 +1,734 @@
# 多显示器 / 显示器切换显示异常 — 根因分析与解决方案
## 问题描述
程序启动后,在多显示器环境或显示器接入/切换(热插拔、主显示器切换)后,widget 和 wallpaper 窗口出现显示异常,包括但不限于:窗口出现在屏幕外、窗口定位到错误显示器、桌面层窗口不可见。
---
## 根因分析
### 根因 1:DPI / 坐标单位不一致(P0)
**位置**: `src/Moli.Desktop/Interop/Win32InteropService.cs:147-154`
```csharp
monitors.Add(new MonitorInfo
{
    Id = new MonitorId(native.Flags ? "primary" : id),
    Bounds = ToRectD(native.Monitor),    // ← 物理像素
    WorkArea = ToRectD(native.WorkArea),  // ← 物理像素
    IsPrimary = native.Flags,
    Scale = 1                             // ← 硬编码为 1
});
```
`GetMonitorInfo` 返回的 `MONITORINFOEX.Monitor / WorkArea` 是**物理像素**,但 WPF 的 `Window.Left/Top/Width/Height` 是**设备无关像素(DIP)**。在非 100% 缩放的显示器上(如 150%),两者存在 `Scale` 倍的偏差:
- 150% 缩放的 4K 显示器:物理 bounds = 3840×2160,DIP bounds = 2560×1440
- 若将物理像素 3840 直接赋给 WPF Width,窗口宽度将是设计的 1.5 倍
- 若将 DIP 坐标 1920 赋给物理像素显示器位置 X,窗口将只偏移 2/3 的预期距离
同时 `Scale = 1` 被硬编码,无法用于任何转换计算。
**影响**: 混合 DPI 环境(如笔记本 150% + 外接显示器 100%)下,即使拓扑监听和 WorkerW 匹配都正确,窗口仍会错位或尺寸异常。
**涉及的底层原理**:
- `GetMonitorInfo` → 物理像素坐标
- 获取真实 DPI:`GetDpiForMonitor(hMonitor, MDT_EFFECTIVE_DPI, out dpiX, out dpiY)` → `Scale = dpiX / 96.0`
- 转换公式:`DIP = Physical / Scale`
---
### 根因 2:完全没有显示器变更检测机制(P0)
**位置**: `src/Moli.Desktop/Runtime/DesktopRuntimeCoordinator.cs:260-264`
```csharp
private void ReconcileCurrentMonitors()
{
    var monitors = _interop.GetMonitors();
    _layout.ReconcileMonitors(monitors);
}
```
该方法仅在 `StartAsync` 中调用**一次**。代码中没有任何 `WM_DISPLAYCHANGE`、`SystemEvents.DisplaySettingsChanged` 或 `HwndSource.AddHook` 钩子。
当用户插拔显示器或切换主显示器后,应用完全不感知拓扑变化,窗口仍留在旧坐标上。
**影响**: 显示器变更后,所有 surface 窗口的屏幕坐标失效,widget 可能显示在已不存在的显示器区域。
---
### 根因 3:WorkerW 策略在多显示器下的两个问题(P0)
#### 问题 A:只取第一个 WorkerW,未区分显示器
**位置**: `src/Moli.Desktop/Interop/WorkerWDesktopLayerStrategy.cs:96-105`
```csharp
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);
```
所有 Desptop 层的 window 都被 reparent 到同一个 WorkerW。
#### 问题 B:SetParent 后使用屏幕绝对坐标,未转为父客户区坐标
**位置**: `src/Moli.Desktop/Interop/WorkerWDesktopLayerStrategy.cs:48-55`
```csharp
NativeMethods.SetWindowPos(
    hwnd, IntPtr.Zero,
    (int)bounds.X, (int)bounds.Y,   // ← 屏幕绝对坐标
    (int)bounds.Width, (int)bounds.Height,
    ...);
```
`SetParent` 后,子窗口的坐标是相对父窗口**客户区原点**的。若 WorkerW 的原点是该显示器左上角,副屏 widget(屏幕坐标 X=2560)需要减去显示器原点(2560→0),否则子窗口坐标超出父窗口区域不可见。
代码中没有调用 `GetWindowRect` 获取 WorkerW 的屏幕位置,也没有 `ScreenToClient` 或 `MapWindowPoints` 做坐标转换。
**关于 WorkerW 拓扑的事实**(澄清原有假设):
Win10/11 上,Explorer 的 WorkerW 存在两种常见形态:
1. **单 WorkerW 横跨虚拟桌面**: 一个 WorkerW 覆盖所有显示器组合成的虚拟桌面区域(如 3840×1080)。此时子窗口坐标就是屏幕绝对坐标,SetParent 后无需额外变换。
2. **每屏一个 WorkerW**: 每个显示器对应一个独立的 WorkerW,原点即该显示器左上角。
实现必须同时覆盖两种形态:先判断 WorkerW 的 `GetWindowRect` 是否覆盖多个显示器区域,再决定坐标策略。
**影响**: 桌面层窗口在非首屏上不可见或位置错误。
---
### 根因 4:主显示器 MonitorId 固定为语义 ID "primary"(P1)
**位置**: `src/Moli.Desktop/Interop/Win32InteropService.cs:148-149`
```csharp
Id = new MonitorId(native.Flags ? "primary" : id),
```
主显示器的 MonitorId 始终为 `"primary"`(忽略真实设备名如 `\\.\DISPLAY1`),非主显示器才使用设备名。`IsPrimary` 字段本身已标记主显示器,ID 中的语义信息是冗余的。
**影响**: 用户切换主显示器后,之前保存 `"primary"` 的 widget 布局直接映射到新主显示器;保存设备名的 widget 可能因原显示器不再是主显示器而匹配异常。
**DeviceName 稳定性限制**: `\\.\DISPLAYn` 在重插、驱动重装、拓扑变化后编号可能变化,并非完全稳定的身份标识。更稳健的方案需要 `QueryDisplayConfig` 获取设备实例路径或使用适配器名称作为备选。本文方案 3 中会额外讨论这一点。
---
### 根因 5:拖拽跨屏拖放不更新 MonitorId(P1)
**位置**: `src/Moli.Desktop/Windows/WidgetWindow.cs:216-228`
```csharp
private async void OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    var bounds = new RectD(Left, Top, Width, Height);
    await _commitLayoutAsync(_layout.InstanceId,
        new WidgetLayoutPatch { Bounds = bounds },    // ← 只有 Bounds,没有 MonitorId
        CancellationToken.None);
}
```
用户将 widget 从一个显示器拖到另一个显示器后,`MonitorId` 仍指向原显示器。后续 `ReconcileMonitors` 按错误的 MonitorId 约束,可能导致 widget 被推回原显示器或裁剪异常。
**影响**: 跨屏拖放后布局身份与位置不一致,约束/持久化均出错。
---
### 根因 6:Wallpaper 仅覆盖单个显示器(P2)
**位置**: `src/Moli.Desktop/Windows/RuntimeSurfaceController.cs:128-137`
```csharp
var monitor = _interop.GetMonitors()
    .FirstOrDefault(monitor => monitor.IsPrimary)
    ?? _interop.GetMonitors().First();
_wallpaper = new WallpaperWindow(plugin, monitor, ...);
```
**影响**: 多屏用户只能在主显示器看到 wallpaper。
---
### 根因 7:LayoutManager 不更新运行时 MonitorSnapshot(P3)
**位置**: `src/Moli.Desktop/Layout/LayoutManager.cs:128-169`
`ReconcileMonitors` 只更新 `_document.Instances`,不更新 `_document.Monitors`。`FindLatestMonitor()` 从 `_document.Monitors` 读取最后一次持久化的快照,而非当前实际显示器数据。
**影响**: reconcile 之后的 `Constrain` 计算可能使用过期显示器 bounds。
---
## 解决方案
---
### 方案 1:统一 DPI 坐标获取与转换 ✓NEW
**概述**: 在 `GetMonitors()` 中获取真实 DPI 并填充 `Scale`,所有窗口定位使用 DIP 坐标,在需要物理像素的 Win32 调用处做转换。
**修改点**:
1. `NativeMethods.cs` 新增 P/Invoke:
```csharp
// 获取每个显示器的有效 DPI
[DllImport("shcore.dll", SetLastError = true)]
internal static extern int GetDpiForMonitor(
    IntPtr hMonitor, int dpiType, out uint dpiX, out uint dpiY);
internal const int MDT_EFFECTIVE_DPI = 0;
```
2. `Win32InteropService.GetMonitors()` 填充真实 Scale,并将 Bounds/WorkArea 转为 DIP:
```csharp
monitors.Add(new MonitorInfo
{
    Id = new MonitorId(id),
    Bounds = ToRectD(native.Monitor),       // 物理像素,暂存
    WorkArea = ToRectD(native.WorkArea),     // 物理像素,暂存
    IsPrimary = native.Flags,
    Scale = scale                            // 从 GetDpiForMonitor 获取
});
// 在循环结束后统一转换
// Bounds / WorkArea 统一转为 DIP 供上层使用
monitor.Bounds = new RectD(
    monitor.Bounds.X / monitor.Scale,
    monitor.Bounds.Y / monitor.Scale,
    monitor.Bounds.Width / monitor.Scale,
    monitor.Bounds.Height / monitor.Scale);
// WorkArea 同理
```
3. 所有 `SetWindowPos` 调用处(`WorkerWDesktopLayerStrategy`、`BottomDesktopLayerStrategy`)需要将 DIP 坐标还原为物理像素:
```csharp
// WidgetWindow / WallpaperWindow 传递 DIP bounds
// 在 Win32 调用前转换
var physicalX = (int)(dipBounds.X * monitor.Scale);
var physicalY = (int)(dipBounds.Y * monitor.Scale);
var physicalW = (int)(dipBounds.Width * monitor.Scale);
var physicalH = (int)(dipBounds.Height * monitor.Scale);
```
4. WPF 的 `Window.Left/Top/Width/Height` 本身就是 DIP,所以从 layout 读取的值直接赋给 WPF 窗口,无需额外转换。关键是要保证存储到 layout 的坐标已经是 DIP。
**涉及文件**:
- `src/Moli.Desktop/Interop/NativeMethods.cs`
- `src/Moli.Desktop/Interop/Win32InteropService.cs`
- `src/Moli.Desktop/Interop/WorkerWDesktopLayerStrategy.cs`
- `src/Moli.Desktop/Interop/BottomDesktopLayerStrategy.cs`
---
### 方案 2:添加显示器变更监听(常驻消息窗口)
**概述**: 在应用级别创建常驻消息窗口,监听 `WM_DISPLAYCHANGE` 及其他拓扑相关消息,触发完整的显示器拓扑同步。
**关键修正**: 不能挂在 `ManagementWindow` 上(该窗口按需创建、可能被关闭)。应创建应用级常驻隐藏窗口或挂载在 `TrayShell` / `Application.MainWindow` 上。
**实现方式**:
创建 `DisplayChangeMonitor` 服务类,内部维护一个隐藏的 `HwndSource`:
```csharp
public sealed class DisplayChangeMonitor : IDisposable
{
    private HwndSource? _source;
    private CancellationTokenSource? _debounceCts;
    private readonly SemaphoreSlim _syncLock = new(1, 1);
    private readonly IDesktopRuntime _runtime;
    public void Start()
    {
        var parameters = new HwndSourceParameters("MoliDisplayMonitor")
        {
            Width = 0, Height = 0,
            WindowStyle = 0,
            ExtendedWindowStyle = NativeMethods.WsExToolWindow | NativeMethods.WsExNoActivate
        };
        _source = new HwndSource(parameters);
        _source.AddHook(WndProc);
    }
    private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
    {
        const int WM_DISPLAYCHANGE = 0x007E;
        const int WM_SETTINGCHANGE = 0x001A;
        const int WM_DEVICECHANGE = 0x0219;
        if (msg is WM_DISPLAYCHANGE or WM_SETTINGCHANGE or WM_DEVICECHANGE)
        {
            DebounceReconcileAsync();
        }
        return IntPtr.Zero;
    }
    private void DebounceReconcileAsync()
    {
        _debounceCts?.Cancel();
        _debounceCts = new CancellationTokenSource();
        var token = _debounceCts.Token;
        // 防抖 500ms,避免连续消息触发多次 reconcile
        Task.Delay(500, token).ContinueWith(async _ =>
        {
            if (token.IsCancellationRequested) return;
            await _syncLock.WaitAsync();
            try
            {
                await Application.Current.Dispatcher.InvokeAsync(async () =>
                    await _runtime.OnDisplayTopologyChangedAsync(CancellationToken.None));
            }
            finally { _syncLock.Release(); }
        }, token);
    }
    public void Dispose()
    {
        _debounceCts?.Cancel();
        _source?.Dispose();
    }
}
```
**同步逻辑**(`IDesktopRuntime` 新增 `OnDisplayTopologyChangedAsync`):
```
OnDisplayTopologyChangedAsync:
  1. 防抖等待(DebounceReconcileAsync 已处理)
  2. 获取最新显示器列表 → _interop.GetMonitors()
  3. 调用 _layout.ReconcileMonitors(monitors) 迁移 widget
  4. 调用 _layout.SaveAsync() 持久化
  5. 调用 _surfaces.SyncAllLayoutsAsync(monitors) 重新应用所有窗口布局
  6. 调用 _surfaces.SyncWallpaperMonitorsAsync(monitors) 同步 wallpaper
  7. 对 Desktop 层窗口重新调用 MoveToDesktopLayer(WorkerW 可能已重建)
```
**`IRuntimeSurfaceController` 需要新增的方法**:
```csharp
// 同步所有现有 widget 窗口的布局
Task SyncAllLayoutsAsync(IReadOnlyList<MonitorInfo> monitors, CancellationToken ct);
// 同步 wallpaper(创建/销毁/重定位)
Task SyncWallpaperMonitorsAsync(IReadOnlyList<MonitorInfo> monitors, CancellationToken ct);
// 重建所有 Desktop 层窗口的 WorkerW 附着
Task ReattachDesktopLayersAsync(IReadOnlyList<MonitorInfo> monitors, CancellationToken ct);
```
**涉及文件**:
- `src/Moli.Desktop/Runtime/DesktopRuntimeCoordinator.cs`
- `src/Moli.Desktop/Runtime/IDesktopRuntime.cs`
- `src/Moli.Desktop/Runtime/IRuntimeSurfaceController.cs`
- `src/Moli.Desktop/Windows/RuntimeSurfaceController.cs`
- 新建 `src/Moli.Desktop/Interop/DisplayChangeMonitor.cs`(或放在 Host 层)
---
### 方案 3:WorkerW 按显示器匹配 + 坐标转换
**概述**: 收集所有 WorkerW 句柄及屏幕位置,根据其拓扑形态(单横跨或多独立)决定匹配和坐标转换策略。
**实现步骤**:
1. 收集所有包含 `SHELLDLL_DefView` 子窗口的 WorkerW,记录其 HWND 和屏幕 Rect:
```csharp
private static List<(IntPtr Hwnd, NativeMethods.Rect ScreenRect)> EnumerateWorkerWindows()
{
    var results = new List<(IntPtr, NativeMethods.Rect)>();
    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.GetWindowRect(workerW, out var rect))
        {
            results.Add((workerW, rect));
        }
        return true;
    }, IntPtr.Zero);
    return results;
}
```
2. 判断 WorkerW 拓扑形态并选择匹配策略:
```
if (workerWs.Count == 1 && workerW 横跨多个显示器区域)
    → 单 WorkerW 模式:直接用这一个 WorkerW,不需要 per-monitor 匹配
    → 坐标转换:子窗口坐标 = 屏幕绝对坐标(WorkerW 原点即虚拟桌面原点)
else (每屏一个 WorkerW)
    → 按重叠面积匹配 WorkerW 与 MonitorInfo.Bounds
    → 坐标转换:子窗口坐标 = 屏幕绝对坐标 - WorkerW 原点坐标(MapWindowPoints 或手动计算)
```
3. 匹配时使用**重叠面积最大**而非 X/Y 精确相等(DPI 缩放或窗口边框可能导致微小偏差):
```csharp
private static IntPtr? FindBestWorkerW(
    RectD monitorBounds,
    List<(IntPtr Hwnd, NativeMethods.Rect ScreenRect)> workerWs)
{
    (IntPtr Hwnd, double Overlap) best = (IntPtr.Zero, 0);
    foreach (var (hwnd, rect) in workerWs)
    {
        var wr = new RectD(rect.Left, rect.Top,
            rect.Right - rect.Left, rect.Bottom - rect.Top);
        var overlap = IntersectionArea(monitorBounds, wr);
        if (overlap > best.Overlap)
            best = (hwnd, overlap);
    }
    return best.Hwnd != IntPtr.Zero ? best.Hwnd : null;
}
```
4. `TryAttachDesktopWindow` 在 `SetWindowPos` 前做坐标转换:
```csharp
// 单横跨 WorkerW:屏幕坐标即子窗口坐标
// 每屏 WorkerW:减去 WorkerW 原点
int childX = (int)bounds.X;
int childY = (int)bounds.Y;
if (!isSingleSpanningWorkerW)
{
    childX -= workerWRect.Left;
    childY -= workerWRect.Top;
}
NativeMethods.SetWindowPos(hwnd, IntPtr.Zero,
    childX, childY, (int)bounds.Width, (int)bounds.Height, ...);
```
5. `IWin32InteropService.MoveToDesktopLayer` 扩展为传递 `MonitorInfo`(含 Scale,方案 1):
```csharp
void MoveToDesktopLayer(IntPtr hwnd, DesktopLayerMode mode,
    RectD dipBounds, MonitorInfo monitor);
```
6. 维护 WorkerW 映射缓存,在显示器变更时通过 `ReattachDesktopLayersAsync` 重建。
**涉及文件**:
- `src/Moli.Desktop/Interop/WorkerWDesktopLayerStrategy.cs`
- `src/Moli.Desktop/Interop/IDesktopLayerStrategy.cs`
- `src/Moli.Desktop/Interop/IWin32InteropService.cs`
- `src/Moli.Desktop/Interop/Win32InteropService.cs`
- `src/Moli.Desktop/Interop/NativeMethods.cs`(新增 `GetWindowRect` P/Invoke)
- `src/Moli.Desktop/Windows/WidgetWindow.cs`
- `src/Moli.Desktop/Windows/WallpaperWindow.cs`
---
### 方案 4:MonitorId 使用设备名 + "primary" 显式迁移
**概述**:
- `GetMonitors()` 中移除 `"primary"` 语义 ID,统一使用设备名
- 在 `LayoutManager` 加载/Reconcile 时,将旧的 `"primary"` 显式映射为当前主显示器的设备名,避免所有旧布局被当作孤儿
**步骤 1 — Win32InteropService 不再覆盖 ID**:
```diff
- Id = new MonitorId(native.Flags ? "primary" : id),
+ Id = new MonitorId(id),
```
**步骤 2 — LayoutManager 增加迁移逻辑**:
在 `ReconcileMonitors` 中,对 `MonitorId == "primary"` 的旧布局做显式迁移:
```csharp
// ReconcileMonitors 内
var primary = monitors.FirstOrDefault(m => m.IsPrimary) ?? monitors[0];
if (layout.MonitorId.Value == "primary")
{
    // 旧 primary → 映射到当前主显示器设备名
    // 尽量保留原相对位置(基于旧文档中最后的 MonitorSnapshot)
    var oldSnapshot = _document.Monitors
        .OrderByDescending(s => s.CapturedAt)
        .FirstOrDefault();
    var oldPrimary = oldSnapshot?.Monitors
        .FirstOrDefault(m => m.Id.Value == "primary");
    if (oldPrimary is not null)
    {
        // 有旧快照:按旧主屏和新主屏的比例缩放位置
        layout = ScaleLayoutBetweenMonitors(layout, oldPrimary, primary);
    }
    else
    {
        // 无快照:居中到新主屏
        layout = CenterInMonitor(layout, primary);
    }
    _document.Instances[i] = layout;
    continue;
}
```
**步骤 3 — DeviceName 稳定性说明**:
`\\.\DISPLAYn` 在以下场景可能变化:
- USB-C/Thunderbolt 显示器重新插拔
- 显卡驱动更新
- Windows 显示拓扑重置
短期(同一次 Windows 会话内)设备名稳定;长期可考虑更稳健的身份标识:
- 使用 `QueryDisplayConfig` + `DISPLAYCONFIG_PATH_INFO` 获取设备实例路径
- 或组合适配器名称 + 序列号(通过 WMI `Win32_DesktopMonitor`)
- 或回退策略:当设备名匹配失败时,按重叠面积匹配(与方案 3 的 WorkerW 匹配类似)
**涉及文件**:
- `src/Moli.Desktop/Interop/Win32InteropService.cs`
- `src/Moli.Desktop/Layout/LayoutManager.cs`
---
### 方案 5:拖拽松手时重新计算 MonitorId
**概述**: `WidgetWindow.OnMouseLeftButtonUp` 提交布局时,根据 widget 中心点所在显示器更新 MonitorId。
**修改点**:
`src/Moli.Desktop/Windows/WidgetWindow.cs:216-228`:
```diff
  private async void OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
  {
      var bounds = new RectD(Left, Top, Width, Height);
+     var centerX = bounds.X + bounds.Width / 2;
+     var centerY = bounds.Y + bounds.Height / 2;
+     var monitorId = _interop.GetMonitors()
+         .FirstOrDefault(m => centerX >= m.Bounds.X
+             && centerX < m.Bounds.Right
+             && centerY >= m.Bounds.Y
+             && centerY < m.Bounds.Bottom)
+         ?.Id ?? _layout.MonitorId;
      await _commitLayoutAsync(_layout.InstanceId,
-         new WidgetLayoutPatch { Bounds = bounds },
+         new WidgetLayoutPatch { Bounds = bounds, MonitorId = monitorId },
          CancellationToken.None);
  }
```
WidgetWindow 需要持有 `IWin32InteropService` 引用(当前构造函数没有)。
**更稳健的方案**: 根据 widget 与各显示器的**可见面积重叠最大者**确定 MonitorId,而非仅中点判断(widget 可能横跨两个显示器)。
**涉及文件**:
- `src/Moli.Desktop/Windows/WidgetWindow.cs`
---
### 方案 6:Wallpaper 支持多显示器
**概述**: 将单个 `_wallpaper` 改为每个显示器一个 `WallpaperWindow`。
**修改点**:
1. `RuntimeSurfaceController` 中将 `_wallpaper` 改为字典:
```csharp
private readonly Dictionary<MonitorId, WallpaperWindow> _wallpapers = [];
```
2. `EnableWallpaperAsync` 为所有显示器创建 WallpaperWindow:
```csharp
public Task EnableWallpaperAsync(WallpaperRuntimeState wallpaper, ...)
{
    var monitors = _interop.GetMonitors();
    foreach (var monitor in monitors)
    {
        var wallWin = new WallpaperWindow(plugin, monitor, ...);
        _wallpapers[monitor.Id] = wallWin;
        wallWin.Show();
    }
}
```
3. `DisableWallpaperAsync` 关闭所有。
4. `SyncWallpaperMonitorsAsync`(方案 2 联动):对比新旧显示器列表,创建新增的、销毁移除的。
**NFR 注意 — WebView2 资源成本**: 每个 WallpaperWindow 持有独立的 WebView2 实例,多显示器意味着多倍内存/GPU 开销。需评估:
- 是否允许用户配置"仅主屏壁纸" vs "全屏壁纸"
- 是否暂停不可见显示屏的 WebView 渲染(`TrySuspendAsync` / `Resume`)
- 是否共享 WebView 实例(复杂,当前架构不推荐)
这些决策影响方案 6 的优先级是否保持 P2 或降级。
**涉及文件**:
- `src/Moli.Desktop/Windows/RuntimeSurfaceController.cs`
- `src/Moli.Desktop/Runtime/IRuntimeSurfaceController.cs`
- `src/Moli.Desktop/Runtime/DesktopRuntimeCoordinator.cs`
---
### 方案 7:ReconcileMonitors 时更新 MonitorSnapshot + 分辨率/Dpi 变化策略
**概述**:
- 在 reconcile 完成后将当前显示器快照追加到 `_document.Monitors`
- 明确分辨率/DPI 变化时 widget 布局的保留策略
**修改点 A — 更新快照**:
```diff
  lock (_gate)
  {
      for (var i = 0; i < _document.Instances.Count; i++)
      {
          // ... 现有 reconcile 逻辑 ...
      }
+     _document.Monitors.Add(new MonitorSnapshot
+     {
+         CapturedAt = DateTimeOffset.UtcNow,
+         Monitors = [.. monitors]
+     });
+
+     // 限制快照数量,仅保留最近 5 个
+     while (_document.Monitors.Count > 5)
+         _document.Monitors.RemoveAt(0);
      return [.. _document.Instances];
  }
```
**修改点 B — 分辨率/DPI 变化的布局策略**:
当前 `Constrain` 方法仅做钳制(clamp),不按比例缩放。当显示器分辨率变化时(如 1080p→4K 或相反),widget 位置仅保证在可见区域内,不会按相对比例保留。
建议明确策略(二选一):
| 策略 | 行为 | 适用场景 |
|------|------|----------|
| **钳制(当前)** | 保持绝对位置和大小,仅保证在 work area 内 | 临时分辨率变化(如游戏全屏) |
| **相对比例缩放** | 按 work area 比例缩放位置和大小 | 持久性显示器切换(不同分辨率的显示器) |
实现相对比例缩放:
```csharp
// 在 ReconcileMonitors 中,当 monitor.Id 匹配但 work area 尺寸变化时
if (oldMonitor is not null &&
    (oldMonitor.WorkArea.Width != monitor.WorkArea.Width ||
     oldMonitor.WorkArea.Height != monitor.WorkArea.Height))
{
    var ratioX = monitor.WorkArea.Width / oldMonitor.WorkArea.Width;
    var ratioY = monitor.WorkArea.Height / oldMonitor.WorkArea.Height;
    layout = layout with
    {
        Bounds = new RectD(
            monitor.WorkArea.X + (layout.Bounds.X - oldMonitor.WorkArea.X) * ratioX,
            monitor.WorkArea.Y + (layout.Bounds.Y - oldMonitor.WorkArea.Y) * ratioY,
            layout.Bounds.Width * ratioX,
            layout.Bounds.Height * ratioY)
    };
}
```
此策略需与产品确认。
**涉及文件**:
- `src/Moli.Desktop/Layout/LayoutManager.cs`
---
### 补充方案 A:Explorer 重启 / WorkerW 失效检测
**问题**: 睡眠/唤醒、杀掉 explorer.exe、Win+D 等场景可能导致 WorkerW 句柄失效,但不一定触发 `WM_DISPLAYCHANGE`。
**建议**:
- 在 `ReattachDesktopLayersAsync` 中,每次先校验已缓存的 WorkerW 句柄是否仍然有效(`IsWindow(hwnd)`)
- 若失效则重新枚举 WorkerW 并重建映射
- 周期性(如每 30 秒)做一次轻量校验(仅 `IsWindow`,不重建)
此逻辑应内置在方案 3 的 WorkerW 映射缓存中。
---
### 补充方案 B:BottomDesktopLayerStrategy 降级路径的 DPI 修复
`BottomDesktopLayerStrategy` 同样使用屏幕绝对坐标调用 `SetWindowPos`,且不区分显示器。在方案 1(DPI)和方案 3(坐标转换)修复后,该降级路径应同步使用物理像素转换后的坐标。
---
### 补充方案 C:诊断码扩展
建议新增诊断事件码:
- `DisplayTopologyChanged` — 显示器拓扑变更
- `WorkerWRemapped` — WorkerW 映射重建
- `LayoutMigratedFromPrimary` — 旧 "primary" 布局迁移
- `WorkerWValidationFailed` — WorkerW 句柄失效需重建
便于验收和排障。
---
## 实施优先级
| 优先级 | 方案 | 理由 |
|--------|------|------|
| **P0** | 方案 1(DPI/坐标) | 混合 DPI 下窗口位置/尺寸错误,是最基础的修正 |
| **P0** | 方案 2(变更监听) | 不感知拓扑变化,窗口坐标永久失效 |
| **P0** | 方案 3(WorkerW 匹配+坐标转换) | 桌面层附着是多屏 widget 可见性的前提 |
| **P1** | 方案 4(MonitorId 迁移) | 影响布局持久化正确性,需含"primary"显式迁移 |
| **P1** | 方案 5(拖拽更新 MonitorId) | 跨屏拖放是高频操作,身份不一致导致约束异常 |
| **P2** | 方案 6(多屏 Wallpaper) | 功能增强,需先定产品范围与 WebView 成本 |
| **P2** | 方案 7(快照+布局策略) | 辅助性修复,解决约束计算与分辨率变化 |
| **P2** | 补充方案 A(WorkerW 失效检测) | 覆盖 Explorer 重启等边缘场景 |
| **P3** | 补充方案 B(降级路径) | 仅在 WorkerW 策略失败时触发 |
| **P3** | 补充方案 C(诊断码) | 开发验收辅助 |
---
## 测试验证建议
1. **混合 DPI(100% + 150%)**: 在不同 DPI 缩放的显示器间创建/移动 widget,验证位置和尺寸正确
2. **混合 DPI 下的桌面层**: 副显示器(150%)上 widget 在 Desktop 层可见且位置正确
3. **双显示器 → 单显示器热拔**: 拔掉副显示器,验证副显示器上的 widget 自动迁移到主显示器
4. **单显示器 → 双显示器热插**: 插入副显示器,验证可在新显示器上正常创建 widget
5. **切换主显示器**: 通过 Windows 显示设置切换主显示器,验证 widget 和 wallpaper 正确跟随,无"居中重排"的数据回归
6. **跨屏拖放 widget**: 将 widget 从一个显示器拖到另一个显示器,验证 MonitorId 更新正确
7. **不同分辨率显示器**: 在 1080p 和 4K 显示器间拖拽 widget,验证大小和位置约束正确
8. **睡眠/唤醒**: 系统睡眠再唤醒,验证窗口仍在正确位置且 WorkerW 附着正常(可能需要 Explorer 重启检测)
9. **RDP 远程桌面**: 连接/断开 RDP 会话(会改变显示器拓扑),验证行为正确
10. **Explorer 重启**: 杀掉 explorer.exe 再启动,验证桌面层重新附着
11. **Win+D / 显示桌面**: 验证 WidgetWindow 不被带到前台
---
## 涉及文件清单(最终版 v2)
| 文件 | P0 方案 | P1 方案 | P2 方案 | P3 补充 |
|------|---------|---------|---------|---------|
| `NativeMethods.cs` | ✓ | | | |
| `Win32InteropService.cs` | ✓ | | | |
| `WorkerWDesktopLayerStrategy.cs` | ✓ | | | ✓ |
| `BottomDesktopLayerStrategy.cs` | | | | ✓ |
| `IDesktopLayerStrategy.cs` | ✓ | | | |
| `IWin32InteropService.cs` | ✓ | | | |
| `DesktopRuntimeCoordinator.cs` | ✓ | | ✓ | |
| `IDesktopRuntime.cs` | ✓ | | | |
| `RuntimeSurfaceController.cs` | ✓ | | ✓ | |
| `IRuntimeSurfaceController.cs` | ✓ | | ✓ | |
| `WidgetWindow.cs` | ✓ | ✓ | | |
| `WallpaperWindow.cs` | ✓ | | | |
| `LayoutManager.cs` | | ✓ | ✓ | |
| `DiscoveryChangeMonitor.cs`(新建) | ✓ | | | |
| `DiagnosticCodes.cs` | | | | ✓ |
scripts/publish-to-apps.ps1
@@ -1,7 +1,7 @@
param(
    [string]$Configuration = "Release",
    [string]$Runtime = "win-x64",
    [string]$TargetRoot = "Y:\Application",
    [string]$TargetRoot = "D:\lin\tools\Moli.Desktop\Moli.Desktop",
    [string]$AppName = "Moli.Desktop",
    [switch]$SelfContained,
    [switch]$SkipTests,
src/Moli.Desktop.Tests/Interop/FakeWin32InteropService.cs
@@ -9,8 +9,9 @@
    public bool ClickThroughEnabled { get; private set; }
    public bool ToolWindowEnabled { get; private set; }
    public bool NoActivateEnabled { get; private set; }
    public byte Opacity { get; private set; } = 255;
    public bool LayeredEnabled { get; private set; }
    public DesktopLayerMode? LayerMode { get; private set; }
    public MonitorInfo? LayerMonitor { get; private set; }
    public Moli.Desktop.Layout.RectD? LayerBounds { get; private set; }
    public bool RestoredTopLevel { get; private set; }
@@ -22,17 +23,12 @@
    public void SetNoActivate(IntPtr hwnd, bool enabled) => NoActivateEnabled = enabled;
    public void SetLayered(IntPtr hwnd, bool enabled, byte opacity) => Opacity = enabled ? opacity : (byte)255;
    public void SetLayered(IntPtr hwnd, bool enabled) => LayeredEnabled = enabled;
    public void MoveToDesktopLayer(IntPtr hwnd, DesktopLayerMode mode, MonitorInfo monitor)
    public void MoveToDesktopLayer(IntPtr hwnd, DesktopLayerMode mode, MonitorInfo monitor, Moli.Desktop.Layout.RectD bounds)
    {
        LayerMode = mode;
        LayerBounds = monitor.Bounds;
    }
    public void MoveToDesktopLayer(IntPtr hwnd, DesktopLayerMode mode, Moli.Desktop.Layout.RectD bounds)
    {
        LayerMode = mode;
        LayerMonitor = monitor;
        LayerBounds = bounds;
    }
@@ -47,7 +43,8 @@
            Id = new Moli.Desktop.Layout.MonitorId("primary"),
            Bounds = new Moli.Desktop.Layout.RectD(0, 0, 1920, 1080),
            WorkArea = new Moli.Desktop.Layout.RectD(0, 0, 1920, 1040),
            IsPrimary = true
            IsPrimary = true,
            Scale = 1
        }
    ];
}
src/Moli.Desktop.Tests/Interop/Win32InteropContractTests.cs
@@ -1,3 +1,4 @@
using Moli.Desktop.Configuration;
using Moli.Desktop.Interop;
namespace Moli.Desktop.Tests.Interop;
@@ -13,15 +14,23 @@
        interop.SetClickThrough(hwnd, true);
        interop.SetToolWindow(hwnd, true);
        interop.SetNoActivate(hwnd, true);
        interop.SetLayered(hwnd, true, 128);
        interop.MoveToDesktopLayer(hwnd, DesktopLayerMode.WorkerW, new Moli.Desktop.Layout.RectD(10, 20, 300, 120));
        interop.SetLayered(hwnd, true);
        var monitor = new MonitorInfo
        {
            Id = new Moli.Desktop.Layout.MonitorId("primary"),
            Bounds = new Moli.Desktop.Layout.RectD(0, 0, 1920, 1080),
            WorkArea = new Moli.Desktop.Layout.RectD(0, 0, 1920, 1040),
            IsPrimary = true,
            Scale = 1
        };
        interop.MoveToDesktopLayer(hwnd, DesktopLayerMode.WorkerW, monitor, new Moli.Desktop.Layout.RectD(10, 20, 300, 120));
        interop.RestoreTopLevelWindow(hwnd);
        interop.SetBottomMost(hwnd);
        Assert.True(interop.ClickThroughEnabled);
        Assert.True(interop.ToolWindowEnabled);
        Assert.True(interop.NoActivateEnabled);
        Assert.Equal(128, interop.Opacity);
        Assert.True(interop.LayeredEnabled);
        Assert.Equal(new Moli.Desktop.Layout.RectD(10, 20, 300, 120), interop.LayerBounds);
        Assert.True(interop.RestoredTopLevel);
        Assert.Single(interop.GetMonitors());
src/Moli.Desktop.Tests/Runtime/DesktopRuntimeCoordinatorTests.cs
@@ -169,7 +169,8 @@
                new FakeWin32InteropService(),
                diagnostics,
                events,
                surface);
                surface,
                new DisplayChangeMonitor());
            return new RuntimeFixture(runtime, configuration, events, surface, widgetId);
        }
@@ -237,5 +238,11 @@
        public Task DisableWallpaperAsync(CancellationToken cancellationToken = default) => Task.CompletedTask;
        public Task ShutdownAsync(CancellationToken cancellationToken = default) => Task.CompletedTask;
        public Task SyncAllLayoutsAsync(CancellationToken cancellationToken = default) => Task.CompletedTask;
        public Task SyncWallpaperMonitorsAsync(CancellationToken cancellationToken = default) => Task.CompletedTask;
        public Task ReattachDesktopLayersAsync(CancellationToken cancellationToken = default) => Task.CompletedTask;
    }
}
src/Moli.Desktop/Host/DesktopHostBuilder.cs
@@ -54,6 +54,7 @@
                services.AddSingleton<ILayoutManager, LayoutManager>();
                services.AddSingleton<IDesktopLayerStrategy, WorkerWDesktopLayerStrategy>();
                services.AddSingleton<IDesktopLayerStrategy, BottomDesktopLayerStrategy>();
                services.AddSingleton<DisplayChangeMonitor>();
                services.AddSingleton<IWin32InteropService, Win32InteropService>();
                services.AddSingleton<PluginBridgeDispatcher>();
                services.AddSingleton<IWebViewHostFactory, WebViewHostFactory>();
src/Moli.Desktop/Interop/BottomDesktopLayerStrategy.cs
@@ -1,3 +1,4 @@
using Moli.Desktop.Configuration;
using Moli.Desktop.Diagnostics;
using Moli.Desktop.Layout;
@@ -17,16 +18,22 @@
    public bool IsSupported() => true;
    public bool TryAttachDesktopWindow(IntPtr hwnd, RectD bounds, out string? error)
    public bool TryAttachDesktopWindow(IntPtr hwnd, MonitorInfo monitor, RectD bounds, out string? error)
    {
        error = null;
        var scale = monitor.Scale;
        var x = (int)(bounds.X * scale);
        var y = (int)(bounds.Y * scale);
        var w = (int)(bounds.Width * scale);
        var h = (int)(bounds.Height * scale);
        if (!NativeMethods.SetWindowPos(
            hwnd,
            NativeMethods.HwndBottom,
            (int)bounds.X,
            (int)bounds.Y,
            (int)bounds.Width,
            (int)bounds.Height,
            x,
            y,
            w,
            h,
            NativeMethods.SwpNoActivate | NativeMethods.SwpShowWindow))
        {
            error = $"SetWindowPos failed with {NativeMethods.GetLastError()}";
src/Moli.Desktop/Interop/DisplayChangeMonitor.cs
New file
@@ -0,0 +1,113 @@
using System.Windows;
using System.Windows.Interop;
namespace Moli.Desktop.Interop;
public sealed class DisplayChangeMonitor : IDisposable
{
    private HwndSource? _source;
    private readonly SemaphoreSlim _singleFlight = new(1, 1);
    private readonly int _debounceMs;
    private CancellationTokenSource? _debounceCts;
    private bool _disposed;
    public event Func<Task>? DisplayChanged;
    public DisplayChangeMonitor(int debounceMs = 500)
    {
        _debounceMs = debounceMs;
    }
    public void Start()
    {
        if (_source is not null)
        {
            return;
        }
        try
        {
            var parameters = new HwndSourceParameters("MoliDisplayChangeMonitor")
            {
                WindowStyle = 0,
                ExtendedWindowStyle = 0,
                ParentWindow = NativeMethods.HwndMessage,
            };
            _source = new HwndSource(parameters);
            _source.AddHook(WndProc);
        }
        catch (InvalidOperationException)
        {
            _source = null;
        }
    }
    public void Stop()
    {
        if (_source is null)
        {
            return;
        }
        _source.RemoveHook(WndProc);
        _source.Dispose();
        _source = null;
    }
    public void Dispose()
    {
        if (_disposed)
        {
            return;
        }
        _disposed = true;
        Stop();
        _debounceCts?.Cancel();
        _debounceCts?.Dispose();
        _singleFlight.Dispose();
    }
    private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
    {
        if (msg == NativeMethods.WmDisplayChange
            || msg == NativeMethods.WmSettingChange
            || msg == NativeMethods.WmDeviceChange)
        {
            OnDisplayChanged();
        }
        return IntPtr.Zero;
    }
    private async void OnDisplayChanged()
    {
        _debounceCts?.Cancel();
        _debounceCts?.Dispose();
        _debounceCts = new CancellationTokenSource();
        var token = _debounceCts.Token;
        try
        {
            await Task.Delay(_debounceMs, token).ConfigureAwait(false);
        }
        catch (OperationCanceledException)
        {
            return;
        }
        await _singleFlight.WaitAsync(CancellationToken.None).ConfigureAwait(false);
        try
        {
            if (DisplayChanged is not null)
            {
                await DisplayChanged.Invoke().ConfigureAwait(false);
            }
        }
        finally
        {
            _singleFlight.Release();
        }
    }
}
src/Moli.Desktop/Interop/IDesktopLayerStrategy.cs
@@ -1,3 +1,4 @@
using Moli.Desktop.Configuration;
using Moli.Desktop.Layout;
namespace Moli.Desktop.Interop;
@@ -7,5 +8,5 @@
{
    string Name { get; }
    bool IsSupported();
    bool TryAttachDesktopWindow(IntPtr hwnd, RectD bounds, out string? error);
    bool TryAttachDesktopWindow(IntPtr hwnd, MonitorInfo monitor, RectD bounds, out string? error);
}
src/Moli.Desktop/Interop/IWin32InteropService.cs
@@ -11,9 +11,8 @@
    void SetClickThrough(IntPtr hwnd, bool enabled);
    void SetToolWindow(IntPtr hwnd, bool enabled);
    void SetNoActivate(IntPtr hwnd, bool enabled);
    void SetLayered(IntPtr hwnd, bool enabled, byte opacity);
    void MoveToDesktopLayer(IntPtr hwnd, DesktopLayerMode mode, MonitorInfo monitor);
    void MoveToDesktopLayer(IntPtr hwnd, DesktopLayerMode mode, RectD bounds);
    void SetLayered(IntPtr hwnd, bool enabled);
    void MoveToDesktopLayer(IntPtr hwnd, DesktopLayerMode mode, MonitorInfo monitor, RectD bounds);
    void RestoreTopLevelWindow(IntPtr hwnd);
    void SetBottomMost(IntPtr hwnd);
    IReadOnlyList<MonitorInfo> GetMonitors();
src/Moli.Desktop/Interop/NativeMethods.cs
@@ -15,7 +15,6 @@
    internal const int WsExLayered = 0x00080000;
    internal const int WsExToolWindow = 0x00000080;
    internal const int WsExNoActivate = 0x08000000;
    internal const int LwaAlpha = 0x00000002;
    internal const uint SwpNoSize = 0x0001;
    internal const uint SwpNoMove = 0x0002;
    internal const uint SwpNoZOrder = 0x0004;
@@ -23,7 +22,12 @@
    internal const uint SwpFrameChanged = 0x0020;
    internal const uint SwpShowWindow = 0x0040;
    internal const uint SmtoNormal = 0x0000;
    internal const int WmDisplayChange = 0x007E;
    internal const int WmSettingChange = 0x001A;
    internal const int WmDeviceChange = 0x0219;
    internal const int MdtEffectiveDpi = 0;
    internal static readonly IntPtr HwndBottom = new(1);
    internal static readonly IntPtr HwndMessage = new(-3);
    internal delegate bool EnumWindowsProc(IntPtr hwnd, IntPtr lParam);
    internal delegate bool MonitorEnumProc(IntPtr hMonitor, IntPtr hdcMonitor, ref Rect lprcMonitor, IntPtr dwData);
@@ -39,10 +43,6 @@
    [DllImport("user32.dll", EntryPoint = "SetWindowLongW", SetLastError = true)]
    internal static extern int SetWindowLong32(IntPtr hWnd, int nIndex, int dwNewLong);
    [DllImport("user32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    internal static extern bool SetLayeredWindowAttributes(IntPtr hwnd, uint crKey, byte bAlpha, uint dwFlags);
    [DllImport("user32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
@@ -72,6 +72,17 @@
    [return: MarshalAs(UnmanagedType.Bool)]
    internal static extern bool GetMonitorInfo(IntPtr hMonitor, ref MonitorInfoEx lpmi);
    [DllImport("shcore.dll", SetLastError = false)]
    internal static extern int GetDpiForMonitor(IntPtr hMonitor, int dpiType, out uint dpiX, out uint dpiY);
    [DllImport("user32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    internal static extern bool GetWindowRect(IntPtr hWnd, out Rect lpRect);
    [DllImport("user32.dll", SetLastError = false)]
    [return: MarshalAs(UnmanagedType.Bool)]
    internal static extern bool IsWindow(IntPtr hWnd);
    internal static IntPtr GetWindowLongPtr(IntPtr hwnd, int index)
    {
        return IntPtr.Size == 8
src/Moli.Desktop/Interop/Win32InteropService.cs
@@ -22,7 +22,9 @@
    public void SetClickThrough(IntPtr hwnd, bool enabled)
    {
        SetStyleFlag(hwnd, NativeMethods.WsExLayered | NativeMethods.WsExTransparent, enabled, "SetClickThrough");
        // 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)
@@ -35,19 +37,16 @@
        SetStyleFlag(hwnd, NativeMethods.WsExNoActivate, enabled, "SetNoActivate");
    }
    public void SetLayered(IntPtr hwnd, bool enabled, byte opacity)
    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");
        if (enabled && !NativeMethods.SetLayeredWindowAttributes(hwnd, 0, opacity, NativeMethods.LwaAlpha))
        {
            RecordWin32Failure("SetLayeredWindowAttributes", hwnd);
        }
    }
    public void MoveToDesktopLayer(IntPtr hwnd, DesktopLayerMode mode, MonitorInfo monitor)
        => MoveToDesktopLayer(hwnd, mode, monitor.Bounds);
    public void MoveToDesktopLayer(IntPtr hwnd, DesktopLayerMode mode, RectD bounds)
    public void MoveToDesktopLayer(IntPtr hwnd, DesktopLayerMode mode, MonitorInfo monitor, RectD bounds)
    {
        var candidates = mode == DesktopLayerMode.WorkerW
            ? _strategies.OrderBy(strategy => strategy is WorkerWDesktopLayerStrategy ? 0 : 1)
@@ -60,7 +59,7 @@
                continue;
            }
            if (strategy.TryAttachDesktopWindow(hwnd, bounds, out var error))
            if (strategy.TryAttachDesktopWindow(hwnd, monitor, bounds, out var error))
            {
                return;
            }
@@ -139,16 +138,36 @@
                return true;
            }
            var id = string.IsNullOrWhiteSpace(native.DeviceName)
            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(native.Flags ? "primary" : id),
                Bounds = ToRectD(native.Monitor),
                WorkArea = ToRectD(native.WorkArea),
                Id = new MonitorId(deviceName),
                Bounds = dipBounds,
                WorkArea = dipWorkArea,
                IsPrimary = native.Flags,
                Scale = 1
                Scale = scale
            });
            return true;
        }, IntPtr.Zero);
@@ -160,7 +179,8 @@
                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
                IsPrimary = true,
                Scale = 1
            }];
    }
src/Moli.Desktop/Interop/WorkerWDesktopLayerStrategy.cs
@@ -1,3 +1,4 @@
using Moli.Desktop.Configuration;
using Moli.Desktop.Diagnostics;
using Moli.Desktop.Layout;
@@ -17,18 +18,56 @@
    public bool IsSupported() => NativeMethods.FindWindow("Progman", null) != IntPtr.Zero;
    public bool TryAttachDesktopWindow(IntPtr hwnd, RectD bounds, out string? error)
    public bool TryAttachDesktopWindow(IntPtr hwnd, MonitorInfo monitor, RectD bounds, out string? error)
    {
        error = null;
        var desktopHost = FindDesktopHostWindow(out var hostClass);
        if (desktopHost == IntPtr.Zero)
        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 = "Explorer desktop host window was not found.";
            error = "No WorkerW or Progman desktop host window found.";
            _diagnostics.Record(
                DiagnosticSeverity.Warning,
                DiagnosticCodes.DesktopLayerAttachFailed,
                "Explorer desktop host window was not found.",
                "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;
        }
@@ -45,13 +84,17 @@
            }
        }
        NativeMethods.GetWindowRect(desktopHost, out var hostRect);
        var clientX = physicalX - hostRect.Left;
        var clientY = physicalY - hostRect.Top;
        if (!NativeMethods.SetWindowPos(
            hwnd,
            IntPtr.Zero,
            (int)bounds.X,
            (int)bounds.Y,
            (int)bounds.Width,
            (int)bounds.Height,
            clientX,
            clientY,
            physicalW,
            physicalH,
            NativeMethods.SwpNoZOrder | NativeMethods.SwpNoActivate | NativeMethods.SwpFrameChanged | NativeMethods.SwpShowWindow))
        {
            error = $"SetWindowPos failed with {NativeMethods.GetLastError()}";
@@ -64,13 +107,39 @@
            DiagnosticSeverity.Info,
            DiagnosticCodes.DesktopLayerStrategySelected,
            "Desktop layer strategy selected.",
            new Dictionary<string, string> { ["strategy"] = Name, ["host"] = hostClass });
            new Dictionary<string, string>
            {
                ["strategy"] = Name,
                ["host"] = desktopHost.ToString("X"),
                ["monitorId"] = monitor.Id.Value,
                ["scale"] = scale.ToString("F2")
            });
        return true;
    }
    private static IntPtr FindDesktopHostWindow(out string hostClass)
    private static IntPtr ValidateAndRefreshHandle(
        IntPtr candidate,
        MonitorInfo monitor,
        ref List<(IntPtr hwnd, NativeMethods.Rect rect)> workers)
    {
        hostClass = "WorkerW";
        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)
        {
@@ -92,7 +161,6 @@
                out _);
        }
        IntPtr workerW = IntPtr.Zero;
        NativeMethods.EnumWindows((topHandle, _) =>
        {
            var shellView = NativeMethods.FindWindowEx(topHandle, IntPtr.Zero, "SHELLDLL_DefView", null);
@@ -101,17 +169,64 @@
                return true;
            }
            workerW = NativeMethods.FindWindowEx(IntPtr.Zero, topHandle, "WorkerW", null);
            return workerW == IntPtr.Zero;
        }, IntPtr.Zero);
        if (workerW != IntPtr.Zero)
            var workerW = NativeMethods.FindWindowEx(IntPtr.Zero, topHandle, "WorkerW", null);
            if (workerW != IntPtr.Zero && NativeMethods.IsWindow(workerW) && NativeMethods.GetWindowRect(workerW, out var rect))
        {
            return workerW;
                workers.Add((workerW, rect));
        }
        hostClass = "Progman";
        return progman;
            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)
src/Moli.Desktop/Layout/LayoutManager.cs
@@ -142,12 +142,12 @@
                var monitor = byId.GetValueOrDefault(layout.MonitorId);
                if (monitor is null)
                {
                    var centered = CenterInMonitor(layout, primary);
                    _document.Instances[i] = centered;
                    var migrated = MigrateToPrimary(layout, primary);
                    _document.Instances[i] = migrated;
                    _diagnostics.Record(
                        DiagnosticSeverity.Info,
                        "LayoutReconciled",
                        "Widget layout moved to primary monitor after monitor topology changed.",
                        "Widget layout migrated to primary monitor after monitor topology changed.",
                        new Dictionary<string, string>
                        {
                            ["instanceId"] = layout.InstanceId.Value,
@@ -157,11 +157,22 @@
                    continue;
                }
                var constrained = Constrain(layout, monitor);
                var scaled = ScaleToWorkArea(layout, monitor);
                var constrained = Constrain(scaled, monitor);
                if (constrained != layout)
                {
                    _document.Instances[i] = constrained;
                }
            }
            _document.Monitors.Add(new MonitorSnapshot
            {
                CapturedAt = DateTimeOffset.UtcNow,
                Monitors = [.. monitors]
            });
            while (_document.Monitors.Count > 5)
            {
                _document.Monitors.RemoveAt(0);
            }
            return [.. _document.Instances];
@@ -254,6 +265,62 @@
        };
    }
    private WidgetLayout MigrateToPrimary(WidgetLayout layout, MonitorInfo primary)
    {
        var previousPrimary = _document.Monitors
            .OrderByDescending(snapshot => snapshot.CapturedAt)
            .SelectMany(snapshot => snapshot.Monitors)
            .FirstOrDefault(m => m.IsPrimary);
        if (previousPrimary is null || previousPrimary.WorkArea.Width <= 0 || previousPrimary.WorkArea.Height <= 0)
        {
            return layout with { MonitorId = primary.Id };
        }
        var scaleX = primary.WorkArea.Width / previousPrimary.WorkArea.Width;
        var scaleY = primary.WorkArea.Height / previousPrimary.WorkArea.Height;
        var relX = (layout.Bounds.X - previousPrimary.WorkArea.X) / previousPrimary.WorkArea.Width;
        var relY = (layout.Bounds.Y - previousPrimary.WorkArea.Y) / previousPrimary.WorkArea.Height;
        return ApplyScalarConstraints(layout with
        {
            MonitorId = primary.Id,
            Bounds = new RectD(
                primary.WorkArea.X + relX * primary.WorkArea.Width,
                primary.WorkArea.Y + relY * primary.WorkArea.Height,
                layout.Bounds.Width * scaleX,
                layout.Bounds.Height * scaleY)
        });
    }
    private WidgetLayout ScaleToWorkArea(WidgetLayout layout, MonitorInfo current)
    {
        var previous = _document.Monitors
            .OrderByDescending(snapshot => snapshot.CapturedAt)
            .SelectMany(snapshot => snapshot.Monitors)
            .FirstOrDefault(m => m.Id == current.Id);
        if (previous is null || previous.WorkArea == current.WorkArea ||
            previous.WorkArea.Width <= 0 || previous.WorkArea.Height <= 0)
        {
            return layout;
        }
        var scaleX = current.WorkArea.Width / previous.WorkArea.Width;
        var scaleY = current.WorkArea.Height / previous.WorkArea.Height;
        var relX = (layout.Bounds.X - previous.WorkArea.X) / previous.WorkArea.Width;
        var relY = (layout.Bounds.Y - previous.WorkArea.Y) / previous.WorkArea.Height;
        return layout with
        {
            Bounds = new RectD(
                current.WorkArea.X + relX * current.WorkArea.Width,
                current.WorkArea.Y + relY * current.WorkArea.Height,
                layout.Bounds.Width * scaleX,
                layout.Bounds.Height * scaleY)
        };
    }
    private static double Clamp(double value, double min, double max)
        => Math.Min(Math.Max(value, min), max);
src/Moli.Desktop/Runtime/DesktopRuntimeCoordinator.cs
@@ -15,6 +15,7 @@
    private readonly IDiagnosticsService _diagnostics;
    private readonly IRuntimeEventBus _events;
    private readonly IRuntimeSurfaceController _surfaces;
    private readonly DisplayChangeMonitor _displayMonitor;
    private readonly SemaphoreSlim _lock = new(1, 1);
    private AppSettingsDocument _settings = new();
    private IReadOnlyList<PluginDescriptor> _pluginSnapshot = [];
@@ -30,7 +31,8 @@
        IWin32InteropService interop,
        IDiagnosticsService diagnostics,
        IRuntimeEventBus events,
        IRuntimeSurfaceController surfaces)
        IRuntimeSurfaceController surfaces,
        DisplayChangeMonitor displayMonitor)
    {
        _configuration = configuration;
        _plugins = plugins;
@@ -39,6 +41,7 @@
        _diagnostics = diagnostics;
        _events = events;
        _surfaces = surfaces;
        _displayMonitor = displayMonitor;
    }
    public async Task<OperationResult<AppRuntimeState>> StartAsync(CancellationToken cancellationToken = default)
@@ -61,6 +64,9 @@
            {
                await _surfaces.ApplyWidgetLayoutAsync(ToSurfaceLayout(layout), cancellationToken).ConfigureAwait(false);
            }
            _displayMonitor.DisplayChanged += () => OnDisplayTopologyChangedAsync();
            _displayMonitor.Start();
            _diagnostics.Record(DiagnosticSeverity.Info, DiagnosticCodes.ApplicationStarted, "Desktop runtime started.");
            var state = BuildState();
@@ -234,6 +240,27 @@
        }
    }
    public async Task OnDisplayTopologyChangedAsync(CancellationToken cancellationToken = default)
    {
        await _lock.WaitAsync(cancellationToken).ConfigureAwait(false);
        try
        {
            ReconcileCurrentMonitors();
            await _layout.SaveAsync(cancellationToken).ConfigureAwait(false);
            await _surfaces.SyncAllLayoutsAsync(cancellationToken).ConfigureAwait(false);
            await _surfaces.SyncWallpaperMonitorsAsync(cancellationToken).ConfigureAwait(false);
            await _surfaces.ReattachDesktopLayersAsync(cancellationToken).ConfigureAwait(false);
            var state = BuildState();
            await _events.PublishAsync(new RuntimeEvent { Name = "display.topologyChanged", Payload = state }, cancellationToken).ConfigureAwait(false);
            await PublishStatusAsync(state, cancellationToken).ConfigureAwait(false);
        }
        finally
        {
            _lock.Release();
        }
    }
    private async Task<OperationResult<AppRuntimeState>> UpdateRuntimeFlagAsync(
        string eventName,
        Action update,
src/Moli.Desktop/Runtime/IDesktopRuntime.cs
@@ -18,4 +18,5 @@
        WidgetInstanceId instanceId,
        WidgetLayoutPatch patch,
        CancellationToken cancellationToken = default);
    Task OnDisplayTopologyChangedAsync(CancellationToken cancellationToken = default);
}
src/Moli.Desktop/Runtime/IRuntimeSurfaceController.cs
@@ -11,4 +11,7 @@
    Task EnableWallpaperAsync(WallpaperRuntimeState wallpaper, CancellationToken cancellationToken = default);
    Task DisableWallpaperAsync(CancellationToken cancellationToken = default);
    Task ShutdownAsync(CancellationToken cancellationToken = default);
    Task SyncAllLayoutsAsync(CancellationToken cancellationToken = default);
    Task SyncWallpaperMonitorsAsync(CancellationToken cancellationToken = default);
    Task ReattachDesktopLayersAsync(CancellationToken cancellationToken = default);
}
src/Moli.Desktop/Windows/RuntimeSurfaceController.cs
@@ -24,7 +24,7 @@
    private readonly IServiceProvider _services;
    private readonly IRuntimeEventBus _events;
    private readonly Dictionary<WidgetInstanceId, WidgetWindow> _widgets = [];
    private WallpaperWindow? _wallpaper;
    private readonly Dictionary<MonitorId, WallpaperWindow> _wallpapers = [];
    private WallpaperRuntimeState _wallpaperState = new();
    private bool _editMode;
    private bool _safeInputMode;
@@ -64,7 +64,11 @@
        => OnUiThreadAsync(() =>
        {
            _safeInputMode = enabled;
            _wallpaper?.ApplyState(_wallpaperState, _safeInputMode);
            foreach (var wallpaper in _wallpapers.Values)
            {
                wallpaper.ApplyState(_wallpaperState, _safeInputMode);
            }
            foreach (var widget in _widgets.Values)
            {
                widget.SetSafeInputMode(enabled);
@@ -103,6 +107,13 @@
                await window.LoadAsync(cancellationToken).ConfigureAwait(true);
            }
            var monitors = _interop.GetMonitors();
            var monitor = monitors.FirstOrDefault(m => m.Id == layout.MonitorId) ?? monitors.FirstOrDefault();
            if (monitor is not null)
            {
                window.SetMonitorInfo(monitor);
            }
            window.ApplyLayout(layout, _editMode, _safeInputMode);
        });
@@ -125,14 +136,26 @@
                return;
            }
            _wallpaper?.Close();
            foreach (var (_, existing) in _wallpapers)
            {
                existing.Close();
            }
            _wallpapers.Clear();
            _wallpaperState = wallpaper;
            var monitor = _interop.GetMonitors().FirstOrDefault(monitor => monitor.IsPrimary) ?? _interop.GetMonitors().First();
            _wallpaper = new WallpaperWindow(plugin, monitor, _webViews.Create(plugin), _interop, _paths, _diagnostics);
            _wallpaper.Closed += (_, _) => _wallpaper = null;
            _wallpaper.Show();
            await _wallpaper.LoadAsync(wallpaper, cancellationToken).ConfigureAwait(true);
            _wallpaper.ApplyState(wallpaper, _safeInputMode);
            var monitors = _interop.GetMonitors();
            foreach (var monitor in monitors)
            {
                cancellationToken.ThrowIfCancellationRequested();
                var wallpaperWindow = new WallpaperWindow(plugin, monitor, _webViews.Create(plugin), _interop, _paths, _diagnostics);
                _wallpapers[monitor.Id] = wallpaperWindow;
                wallpaperWindow.Closed += (_, _) => _wallpapers.Remove(monitor.Id);
                wallpaperWindow.Show();
                await wallpaperWindow.LoadAsync(wallpaper, cancellationToken).ConfigureAwait(true);
                wallpaperWindow.ApplyState(wallpaper, _safeInputMode);
            }
            ReapplyDesktopWidgetLayers();
        });
@@ -140,8 +163,12 @@
        => OnUiThreadAsync(() =>
        {
            _wallpaperState = _wallpaperState with { IsEnabled = false };
            _wallpaper?.Close();
            _wallpaper = null;
            foreach (var (_, wallpaper) in _wallpapers)
            {
                wallpaper.Close();
            }
            _wallpapers.Clear();
            return Task.CompletedTask;
        });
@@ -154,13 +181,113 @@
            }
            _widgets.Clear();
            _wallpaper?.Close();
            _wallpaper = null;
            foreach (var (_, wallpaper) in _wallpapers)
            {
                wallpaper.Close();
            }
            _wallpapers.Clear();
            _eventSubscription?.Dispose();
            _eventSubscription = null;
            return Task.CompletedTask;
        });
    public Task SyncAllLayoutsAsync(CancellationToken cancellationToken = default)
        => OnUiThreadAsync(() =>
        {
            var monitors = _interop.GetMonitors();
            foreach (var (id, window) in _widgets)
            {
                cancellationToken.ThrowIfCancellationRequested();
                var layout = window.CurrentLayout;
                var monitor = monitors.FirstOrDefault(m => m.Id == layout.MonitorId) ?? monitors.FirstOrDefault();
                if (monitor is not null)
                {
                    window.SetMonitorInfo(monitor);
                }
                window.ApplyLayout(layout, _editMode, _safeInputMode);
            }
            return Task.CompletedTask;
        });
    public Task SyncWallpaperMonitorsAsync(CancellationToken cancellationToken = default)
        => OnUiThreadAsync(async () =>
        {
            if (_wallpaperState.PluginId is null || _wallpapers.Count == 0)
            {
                return;
            }
            var plugin = await _plugins.GetAsync(_wallpaperState.PluginId.Value, cancellationToken).ConfigureAwait(true);
            if (plugin is null)
            {
                return;
            }
            var monitors = _interop.GetMonitors();
            var currentIds = new HashSet<MonitorId>(_wallpapers.Keys);
            var newIds = new HashSet<MonitorId>(monitors.Select(m => m.Id));
            foreach (var removed in currentIds.Where(id => !newIds.Contains(id)))
            {
                if (_wallpapers.TryGetValue(removed, out var removedWindow))
                {
                    removedWindow.Close();
                    _wallpapers.Remove(removed);
                }
            }
            foreach (var monitor in monitors)
            {
                cancellationToken.ThrowIfCancellationRequested();
                if (_wallpapers.TryGetValue(monitor.Id, out var existing))
                {
                    existing.ApplyState(_wallpaperState, _safeInputMode);
                }
                else
                {
                    var wallpaperWindow = new WallpaperWindow(plugin, monitor, _webViews.Create(plugin), _interop, _paths, _diagnostics);
                    _wallpapers[monitor.Id] = wallpaperWindow;
                    wallpaperWindow.Closed += (_, _) => _wallpapers.Remove(monitor.Id);
                    wallpaperWindow.Show();
                    await wallpaperWindow.LoadAsync(_wallpaperState, cancellationToken).ConfigureAwait(true);
                    wallpaperWindow.ApplyState(_wallpaperState, _safeInputMode);
                }
            }
        });
    public Task ReattachDesktopLayersAsync(CancellationToken cancellationToken = default)
        => OnUiThreadAsync(() =>
        {
            var monitors = _interop.GetMonitors();
            foreach (var (_, window) in _widgets.Where(kv => kv.Value.CurrentLayout.DisplayLayer == DisplayLayer.Desktop))
            {
                cancellationToken.ThrowIfCancellationRequested();
                var layout = window.CurrentLayout;
                var monitor = monitors.FirstOrDefault(m => m.Id == layout.MonitorId) ?? monitors.FirstOrDefault();
                if (monitor is not null)
                {
                    window.SetMonitorInfo(monitor);
                }
                window.ApplyLayout(layout, _editMode, _safeInputMode);
            }
            foreach (var (monitorId, wallpaper) in _wallpapers)
            {
                cancellationToken.ThrowIfCancellationRequested();
                var monitor = monitors.FirstOrDefault(m => m.Id == monitorId);
                if (monitor is not null)
                {
                    wallpaper.ApplyState(_wallpaperState, _safeInputMode);
                }
            }
            return Task.CompletedTask;
        });
    private async Task CommitWidgetLayoutAsync(
        WidgetInstanceId instanceId,
        WidgetLayoutPatch patch,
src/Moli.Desktop/Windows/WallpaperWindow.cs
@@ -23,7 +23,6 @@
    private readonly DesktopPaths _paths;
    private readonly IDiagnosticsService _diagnostics;
    private bool _clickThrough = true;
    private double _opacity = 1;
    public WallpaperWindow(
        PluginDescriptor plugin,
@@ -59,7 +58,7 @@
    public async Task LoadAsync(WallpaperRuntimeState state, CancellationToken cancellationToken = default)
    {
        _clickThrough = state.ClickThrough;
        _opacity = state.Opacity;
        Opacity = Math.Clamp(state.Opacity, 0.1, 1.0);
        await _webView.InitializeAsync(new WebViewHostOptions
        {
            UserDataFolder = Path.Combine(_paths.WebViewDataDirectory, "wallpaper", _plugin.Id.Value),
@@ -77,7 +76,6 @@
    public void ApplyState(WallpaperRuntimeState state, bool safeInputMode)
    {
        _clickThrough = !safeInputMode && state.ClickThrough;
        _opacity = state.Opacity;
        Opacity = Math.Clamp(state.Opacity, 0.1, 1.0);
        ApplyWin32Styles();
    }
@@ -124,9 +122,9 @@
        {
            _interop.SetToolWindow(hwnd, true);
            _interop.SetNoActivate(hwnd, true);
            _interop.SetLayered(hwnd, true, ToAlpha(_opacity));
            _interop.SetLayered(hwnd, true);
            _interop.SetClickThrough(hwnd, _clickThrough);
            _interop.MoveToDesktopLayer(hwnd, DesktopLayerMode.WorkerW, _monitor);
            _interop.MoveToDesktopLayer(hwnd, DesktopLayerMode.WorkerW, _monitor, _monitor.Bounds);
        }
        catch (Exception ex)
        {
@@ -137,6 +135,4 @@
                new Dictionary<string, string> { ["pluginId"] = _plugin.Id.Value, ["exception"] = ex.GetType().Name });
        }
    }
    private static byte ToAlpha(double opacity) => (byte)Math.Round(Math.Clamp(opacity, 0.1, 1.0) * 255);
}
src/Moli.Desktop/Windows/WidgetWindow.cs
@@ -33,6 +33,7 @@
    private readonly Border _editBorder;
    private readonly Border _resizeGrip;
    private WidgetLayout _layout;
    private MonitorInfo? _monitorInfo;
    private double? _requestedHeight;
    private bool _editMode;
    private bool _safeInputMode;
@@ -163,6 +164,12 @@
        ApplyWin32Styles();
    }
    public void SetMonitorInfo(MonitorInfo? monitorInfo)
    {
        _monitorInfo = monitorInfo;
        ApplyWin32Styles();
    }
    protected override async void OnClosed(EventArgs e)
    {
        await _webView.DisposeAsync();
@@ -224,7 +231,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 +291,13 @@
        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 void ApplyWin32Styles()
    {
        var hwnd = _interop.GetWindowHandle(this);
@@ -275,13 +309,17 @@
        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)
            {
                case DisplayLayer.Desktop:
                    Topmost = false;
                    _interop.MoveToDesktopLayer(hwnd, DesktopLayerMode.WorkerW, _layout.Bounds);
                    if (_monitorInfo is not null)
                    {
                        _interop.MoveToDesktopLayer(hwnd, DesktopLayerMode.WorkerW, _monitorInfo, _layout.Bounds);
                    }
                    break;
                case DisplayLayer.GlobalTop:
                    _interop.RestoreTopLevelWindow(hwnd);
@@ -304,6 +342,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);
}