Hello all,
I've written a few applications which are meant to enable the user to copy text to their clipboard either just by running the application or by clicking on an element in the application GUI. Most of the time, this works perfectly fine:
public static void grab(string text)
{
Clipboard.SetDataObject(text, true);
}
Once in a while, however, a nasty .NET exception dialog would pop up. I wish I had taken a screenshot; but the gist of it was that the clipboard was locked & couldn't be written to.
In order to handle this, I came up with a quick-and-dirty brute force solution that I'm not entirely happy with:
public static void grab(string text)
{
grab(text, 0);
}
private static void grab(string text, int attempt)
{
if (attempt > 5)
return;
try
{
Clipboard.SetDataObject(text, true);
}
catch (Exception)
{
System.Threading.Thread.Sleep(500);
grab(text, ++attempt);
}
}
This appears to work most of the time, but its not very elegant nor is it foolproof, and I was wondering if anyone knows of a better way to deal with this.
Thanks in advance!