# 多显示器 / 显示器切换显示异常 — 根因分析与解决方案 ## 问题描述 程序启动后,在多显示器环境或显示器接入/切换(热插拔、主显示器切换)后,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 monitors, CancellationToken ct); // 同步 wallpaper(创建/销毁/重定位) Task SyncWallpaperMonitorsAsync(IReadOnlyList monitors, CancellationToken ct); // 重建所有 Desktop 层窗口的 WorkerW 附着 Task ReattachDesktopLayersAsync(IReadOnlyList 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 _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` | | | | ✓ |