tags:

views:

1576

answers:

1

Over the course of the last couple of hours I have been tracking down a fairly specific bug with that occurs because another application has the clipboard open. Essentially as the Clipboard is a shared resource (as per "Why does my shared clipboard not work?") and you attempt to execute

Clipboard.SetText(string)

or

Clipboard.Clear().

The following exception is thrown:

System.Runtime.InteropServices.ExternalException: Requested Clipboard operation did not succeed. 
    at System.Windows.Forms.Clipboard.ThrowIfFailed(Int32 hr)
    at System.Windows.Forms.Clipboard.SetDataObject(Object data, Boolean copy, Int32 retryTimes, Int32 retryDelay)
    at System.Windows.Forms.Clipboard.SetText(String text, TextDataFormat format)
    at System.Windows.Forms.Clipboard.SetText(String text)

My initial solution was to retry after a short pause, until I realised that Clipboard.SetDataObject has fields for the number of times and the length of the delay, .NETs default behaviour is to try 10 times with 100msec delay.

There is one final thing that has been noted by the end user, that is despite the exception being thrown the copy to clipboard operation still works, I haven't been able to find any further information about why this may be.

My current solution to the issue is just to silently ignore the exception... is this really the best way?

+6  A: 

As the clipboard is shared by all UI applications, you will run into this from time to time, obviously you don't want your application to crash if it failed to write to the clipboard, so gracefully handling ExternalException is reasonable, i would suggest presenting and error to the user if the setobjectdata call to write to the clipboard fails.

A suggestion would be to use (via p/invoke) user32!GetOpenClipboardWindow to see if another application has the clipboard open, it will return the HWND of the window which has the clipboard open, or IntPtr.Zero if no application had it open, you could spin on the value until it's IntPtr.Zero for a specified amount of time.

Phil Price
I have read up around GetOpenClipboardWindow it seems that that is the best solution to clipboard access issues. Thanks for your reply.
Richard Slater