From 73ee020025a76c0465438c2fd25ed5da81b09372 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sun, 1 Nov 2026 03:43:06 +0800 Subject: [PATCH] =?UTF-8?q?fix(desktop):=20=E5=A4=8D=E5=88=B6=E6=8F=92?= =?UTF-8?q?=E4=BB=B6=E8=B7=AF=E5=BE=84=E4=B8=8D=E5=86=8D=E8=AF=AF=E6=8A=A5?= =?UTF-8?q?=E3=80=8C=E5=89=AA=E8=B4=B4=E6=9D=BF=E8=A2=AB=E5=8D=A0=E7=94=A8?= =?UTF-8?q?=E3=80=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 现场日志显示 6/6 次写入都抛 CLIPBRD_E_CANT_OPEN,但用户粘贴完全正常 —— 根因是远程桌面软件(实测 BilldDesk)长期把剪贴板开着,同时它会把内容同步成 「上次复制的那段文字」,所以剪贴板里本来就是我们要复制的路径。 - 复制前先核对剪贴板内容,已经是目标文本就直接算成功(不再弹占用提示) - 写失败后读回来核对(OleFlushClipboard 失败时数据其实已写入) - 重试改成带截止时间(4 秒)的退避重试,并补一次 OleFlushClipboard - 全部剪贴板操作放到后台 STA 线程(带 5 秒兜底超时),事件处理器改 async, 剪贴板被锁时界面不会卡住 - 真失败时用 GetOpenClipboardWindow 查出占用进程名,写进提示与日志 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- desktop/MainWindow.xaml.cs | 191 +++++++++++++++++++++++++++++++++---- 1 file changed, 171 insertions(+), 20 deletions(-) diff --git a/desktop/MainWindow.xaml.cs b/desktop/MainWindow.xaml.cs index 94cf5a8..2b55a5d 100644 --- a/desktop/MainWindow.xaml.cs +++ b/desktop/MainWindow.xaml.cs @@ -5,6 +5,7 @@ using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; +using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; @@ -869,7 +870,7 @@ public partial class MainWindow : Window /// 「工具 → 复制插件路径(开发者模式)」:插件随安装包释放到 <安装目录>\extension, /// 复制这个 Windows 路径,再到 chrome://extensions「加载已解压的扩展程序」里粘进去。 /// - private void CopyExtensionPath_Click(object sender, RoutedEventArgs e) + private async void CopyExtensionPath_Click(object sender, RoutedEventArgs e) { var path = Path.Combine(AppContext.BaseDirectory, "extension"); if (!Directory.Exists(path)) @@ -880,7 +881,8 @@ public partial class MainWindow : Window return; } - if (TrySetClipboardText(path)) + // 剪贴板被别的程序占着时写入会重试几秒,放到后台做,别把界面卡住 + if (await Task.Run(() => TrySetClipboardText(path))) { AppLog.Write($"已复制谷歌插件地址:{path}"); MessageBox.Show(this, @@ -890,11 +892,18 @@ public partial class MainWindow : Window } AppLog.Write($"复制谷歌插件地址失败(剪贴板被其他程序占用):{path}"); + var holder = GetClipboardHolderName(); + AppLog.Write(holder == null + ? "没查到占用剪贴板的进程" + : $"占用剪贴板的进程:{holder}"); + + var owner = string.IsNullOrEmpty(holder) ? "别的程序" : $"「{holder}」"; var openNotepad = MessageBox.Show(this, - "剪贴板被其他程序占用(输入法 / 剪贴板工具 / 远程桌面都可能),复制失败。\n\n" + - "· 稍等一秒再点一次「复制谷歌插件地址」,通常就好;\n" + - "· 远程桌面里遇到的话,在远程机器上重启 rdpclip.exe 后重试;\n" + - $"· 也可以手动输入这个路径:\n{path}\n\n" + + $"剪贴板正被{owner}占着(远程桌面 / 剪贴板同步工具 / 输入法都会这样),这次没能写进去。\n\n" + + $"· 路径:\n{path}\n" + + "· 如果剪贴板里已经是这个路径,直接粘贴就行,不用管这个提示;\n" + + $"· 关掉{owner},或稍等一两秒再点一次「复制插件路径(开发者模式)」;\n" + + "· 远程桌面里遇到的话,在远程机器上重启 rdpclip.exe 后重试。\n\n" + "要打开记事本显示这个路径吗(方便对照抄写)?", "复制谷歌插件地址", MessageBoxButton.YesNo, MessageBoxImage.Warning); @@ -920,30 +929,170 @@ public partial class MainWindow : Window } /// - /// 写剪贴板:先 WPF 再 WinForms,各自重试几次。 - /// 单次 Clipboard.SetText 在别的进程正持有剪贴板时会直接抛 CLIPBRD_E_CANT_OPEN(0x800401D0)。 + /// 复制到剪贴板:**全部操作放到后台 STA 线程,带超时**,绝不卡住界面。 + /// + /// 现场实测:远程桌面 / 剪贴板同步工具(这台机器上是 BilldDesk)会长期把剪贴板开着, + /// 这时 `OpenClipboard` 直接失败,`OleGetClipboard`(读)甚至会一直阻塞到对方松手 —— + /// 所以连「先核对内容」都得放到后台线程,主线程只等一小会儿。 /// - private static bool TrySetClipboardText(string text) + private static bool TrySetClipboardText(string text) => RunOnStaThread( + () => TrySetClipboardTextCore(text, DateTime.UtcNow + TimeSpan.FromSeconds(4)), + TimeSpan.FromSeconds(5)); + + private static bool TrySetClipboardTextCore(string text, DateTime deadline) { - if (RetryClipboardWrite(() => Clipboard.SetDataObject(text, true), "WPF")) + // 剪贴板里本来就是这段文字(上次复制过 / 上次其实写进去了)→ 直接算成功,别弹「被占用」 + if (ClipboardContainsText(text, 1, deadline)) return true; + + if (WriteClipboard(text, deadline)) return true; + + // 写 API 报错但内容可能已经进去了(OleFlushClipboard 失败时数据仍在) + return ClipboardContainsText(text, 3, deadline); + } + + private static bool WriteClipboard(string text, DateTime deadline) + { + if (RetryClipboardWrite(() => Clipboard.SetDataObject(text, true), "WPF", deadline)) { return true; } - if (RetryClipboardWrite(() => System.Windows.Forms.Clipboard.SetDataObject(text, true), "WinForms")) + if (RetryClipboardWrite(() => System.Windows.Forms.Clipboard.SetDataObject(text, true), "WinForms", deadline)) { return true; } + // 写 API 抛错时最常见的是「OleSetClipboard 成功、OleFlushClipboard 失败」: + // 数据其实已经在剪贴板里了,补一次 flush 让延迟渲染落盘,调用方会再读回来核对 + FlushClipboardRetry(); + return false; + } + + [DllImport("ole32.dll")] + private static extern int OleFlushClipboard(); + + [DllImport("user32.dll")] + private static extern IntPtr GetOpenClipboardWindow(); + + [DllImport("user32.dll")] + private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint processId); + + /// 谁正把剪贴板开着(远程桌面 / 剪贴板同步工具最常见),查不到就返回 null + private static string? GetClipboardHolderName() + { + try + { + var hwnd = GetOpenClipboardWindow(); + if (hwnd == IntPtr.Zero) return null; + + _ = GetWindowThreadProcessId(hwnd, out var processId); + if (processId == 0) return null; + + using var process = Process.GetProcessById((int)processId); + return process.ProcessName; + } + catch + { + return null; + } + } + + /// 补一次 OleFlushClipboard(把「延迟渲染」的数据真正落到剪贴板里) + private static void FlushClipboardRetry() + { + int[] delaysMs = [ 0, 120, 250 ]; + + foreach (var delay in delaysMs) + { + if (delay > 0) + { + Thread.Sleep(delay); + } + + var hr = OleFlushClipboard(); + if (hr >= 0) + { + AppLog.Write("补 OleFlushClipboard 成功,剪贴板数据已落盘"); + return; + } + + AppLog.Write($"补 OleFlushClipboard 失败:0x{hr:X8}"); + } + } + + /// 读回剪贴板核对内容(写失败但实际已写入 / 本来就在里面) + private static bool ClipboardContainsText(string text, int attempts, DateTime deadline) + { + for (var attempt = 1; attempt <= attempts; attempt++) + { + try + { + if (Clipboard.ContainsText() && string.Equals(Clipboard.GetText(), text, StringComparison.Ordinal)) + { + AppLog.Write($"剪贴板内容核对通过(第 {attempt}/{attempts} 次),按复制成功处理"); + return true; + } + } + catch (Exception ex) + { + AppLog.Write($"读剪贴板核对失败(第 {attempt}/{attempts} 次):{ex.Message}"); + } + + if (attempt < attempts) + { + if (DateTime.UtcNow.AddMilliseconds(120) >= deadline) break; + Thread.Sleep(120); + } + } + return false; } - private static bool RetryClipboardWrite(Action write, string api) + /// 在一条新的 STA 线程上执行剪贴板操作(COM 单元干净,超时后不再等,界面不会被卡住) + private static bool RunOnStaThread(Func action, TimeSpan timeout) { - const int attempts = 3; - const int delayMs = 150; + var result = false; + string? error = null; - for (var attempt = 1; attempt <= attempts; attempt++) + var thread = new Thread(() => + { + try + { + result = action(); + } + catch (Exception ex) + { + error = ex.Message; + } + }) + { + IsBackground = true, + Name = "clipboard-op", + }; + + thread.SetApartmentState(ApartmentState.STA); + thread.Start(); + + if (!thread.Join(timeout)) + { + AppLog.Write($"剪贴板操作超时({timeout.TotalSeconds:0} 秒没返回):剪贴板多半被别的程序锁着,先不写了"); + return false; + } + + if (error != null) + { + AppLog.Write($"剪贴板后台线程异常:{error}"); + } + + return result; + } + + private static bool RetryClipboardWrite(Action write, string api, DateTime deadline) + { + // 剪贴板被占通常是「一下子」的事(远程桌面同步、浏览器刚复制完、输入法在读写),退避等一下就好 + int[] delaysMs = [ 150, 300, 500 ]; + + for (var attempt = 1; ; attempt++) { try { @@ -952,15 +1101,17 @@ public partial class MainWindow : Window } catch (Exception ex) { - AppLog.Write($"{api} 写剪贴板失败(第 {attempt}/{attempts} 次):{ex.Message}"); - if (attempt < attempts) + AppLog.Write($"{api} 写剪贴板失败(第 {attempt} 次):{ex.Message}"); + + var delay = attempt <= delaysMs.Length ? delaysMs[attempt - 1] : 500; + if (DateTime.UtcNow.AddMilliseconds(delay) >= deadline) { - Thread.Sleep(delayMs); + return false; } + + Thread.Sleep(delay); } } - - return false; } private void ClearLogs_Click(object sender, RoutedEventArgs e)