GTPCorrgir/ClipboardHelper.cs

58 lines
1.6 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GTPCorrgir
{
public static class ClipboardHelper
{
private static readonly int MaxRetries = 5;
private static readonly int RetryDelay = 100; // milliseconds
public static async Task<bool> SetText(string text)
{
for (int i = 0; i < MaxRetries; i++)
{
try
{
await Task.Delay(RetryDelay);
await System.Windows.Application.Current.Dispatcher.InvokeAsync(() =>
{
System.Windows.Clipboard.SetText(text);
});
return true;
}
catch (Exception)
{
if (i == MaxRetries - 1) throw;
}
}
return false;
}
public static async Task<string> GetText()
{
string text = null;
for (int i = 0; i < MaxRetries; i++)
{
try
{
await Task.Delay(RetryDelay);
text = await System.Windows.Application.Current.Dispatcher.InvokeAsync(() =>
{
return System.Windows.Clipboard.GetText();
});
return text;
}
catch (Exception)
{
if (i == MaxRetries - 1) throw;
}
}
return text;
}
}
}