Clipboard Copying Problem

I recently ran into a problem with the clipboard that is apparently a fairly common problem without a common answer.
The problem occurs while making a temporary copy of the clipboard.

I needed to put something into the clipboard, but I didn't want the user to lose what they already had in there, the easy way that I assumed would work looked like this:

IDataObject oldClipboard = Clipboard.GetDataObject();

//random clipboard manipulation here

Clipboard.SetDataObject(oldClipboard,true);


The true ensures that the data is held in the clipboard even after the program closes.  This solution meets with a "The requested clipboard operation failed" message if there is ever anything actually in the clipboard originally.

 

So here is the proper way of making a copy of the clipboard data, assuming of course that you have no idea what is in the clipboard before you arrived.  An important note if you aren't aware of how the clipboard is structured.  When you copy text out a richtextbox it is actually stored in several different ways:
Rich Text Format
Rich Text Format Without Objects
RTF As Text
System.String
UnicodeText
Text

 

The solution:

IDataObject oldClipboard = Clipboard.GetDataObject();

DataObject newClipboard = new DataObject();

string[] s;

s = oldClipboard.GetFormats(); //gets all the possible formats for that data

foreach(string ns in s)

{

newClipboard.SetData(ns,oldClipboard.GetData(ns)); //re-associate the old data with the proper types

}

//this is where your clipboard manipulation goes.

Clipboard.SetDataObject(newClipboard,true); //true makes sure the data persists