using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; namespace AIK.Views.Utils { public static class SafeClipboard { public static async Task SetTextAsync(string text, int maxRetries = 3, int delayMs = 10) { if (string.IsNullOrEmpty(text)) return false; if (Application.Current?.Dispatcher.CheckAccess() == false) { return await SetTextInternal(text, maxRetries, delayMs); } else { return await SetTextInternal(text, maxRetries, delayMs); } } private static async Task SetTextInternal(string text, int maxRetries, int delayMs) { for (int i = 0; i < maxRetries; i++) { try { Clipboard.SetText(text); return true; } catch (System.Runtime.InteropServices.COMException ex) when (ex.ErrorCode == -2147221040) { if (i == maxRetries - 1) return false; await Task.Delay(delayMs); } } return false; } } }