40 lines
1.1 KiB
C#
40 lines
1.1 KiB
C#
|
|
using System;
|
|||
|
|
using System.Runtime.InteropServices;
|
|||
|
|
using System.Threading;
|
|||
|
|
using System.Windows;
|
|||
|
|
|
|||
|
|
public static class ClipboardHelper
|
|||
|
|
{
|
|||
|
|
/// <summary>
|
|||
|
|
/// 安全复制文本,包含冲突重试机制
|
|||
|
|
/// </summary>
|
|||
|
|
public static void SetText(string text)
|
|||
|
|
{
|
|||
|
|
if (string.IsNullOrEmpty(text)) return;
|
|||
|
|
|
|||
|
|
// 最多尝试 5 次,每次间隔 100 毫秒
|
|||
|
|
for (int i = 0; i < 5; i++)
|
|||
|
|
{
|
|||
|
|
try
|
|||
|
|
{
|
|||
|
|
Clipboard.SetText(text);
|
|||
|
|
return; // 复制成功,退出方法
|
|||
|
|
}
|
|||
|
|
catch (COMException ex)
|
|||
|
|
{
|
|||
|
|
// 如果是剪贴板被占用错误,等待后重试
|
|||
|
|
if ((uint)ex.ErrorCode == 0x800401D0)
|
|||
|
|
{
|
|||
|
|
Thread.Sleep(100);
|
|||
|
|
continue;
|
|||
|
|
}
|
|||
|
|
throw; // 其他 COM 错误则抛出
|
|||
|
|
}
|
|||
|
|
catch (Exception)
|
|||
|
|
{
|
|||
|
|
if (i == 4) throw; // 最后一次尝试失败则抛出
|
|||
|
|
Thread.Sleep(100);
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|