Click here to Skip to main content
15,887,434 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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:

C#
public static void grab(string text)
    {
        grab(text, 0);
    }

private static void grab(string text, int attempt)
    {
        //if no luck after 6 tries, give up.
        if (attempt > 5)
            return;

        try
        {
            Clipboard.SetDataObject(text, true);
        }

        catch (Exception) 
        {
            //Wait half a second, increment attempt counter and then try again
            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!
Posted
Comments
Sergey Alexandrovich Kryukov 17-May-12 12:15pm    
Does it mean that you cannot reproduce the problem? Without understanding it, no solution can be considered valid, forget about reliability. At least encounter this once again and tell us exact message. Is it related to other applications? You solution is not acceptable at all, especially because you use some arbitrary Sleep and attempt count.
--SA
[no name] 17-May-12 12:38pm    
http://msdn.microsoft.com/en-us/library/ms158293

1 solution

Please see my comment to the question.

One problem I can see immediately is: as your object is always a string, you should use Clipboard.SetText, http://msdn.microsoft.com/en-us/library/ydby206k.aspx[^].

From the other hand, if this string carries some special semantic (so, this is some custom object and string is just a media), you should register a custom data format. (Or do you do this already?) This CodeProject article explains the techniques involved:
Clipboard handling with .NET - Part II[^].

—SA
 
Share this answer
 
Comments
Maciej Los 17-May-12 12:59pm    
Good answer, my 5!
Sergey Alexandrovich Kryukov 17-May-12 16:35pm    
Thank you (and you probably forgot to vote it)...
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900