Click here to Skip to main content
13,050,242 members (99,908 online)
Rate this:
Please Sign up or sign in to vote.
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:

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)
            Clipboard.SetDataObject(text, true);
        catch (Exception) 
            //Wait half a second, increment attempt counter and then try again
            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 17-May-12 6:02am
SAKryukov 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.
Wes Aday 17-May-12 12:38pm

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

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,[^].

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[^].

losmac 17-May-12 12:59pm
Good answer, my 5!
SAKryukov 17-May-12 16:35pm
Thank you (and you probably forgot to vote it)...

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

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web02 | 2.8.170713.1 | Last Updated 17 May 2012
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100