I'm trying to write a small application that needs to use the clipboard for some functionality. Since I don't want to overwrite the user's data currently in the clipboard I decided to save it to memory, do my job and then write it back. The code below is a console application that is a barebones example of what I'm trying to do.
The problem I'm having is restoring the state. If I copy something to the clipboard from Visual Studio before running the application there are a total of six objects in the clipboard (various string formats and a locale) which all get put in the cache. Once I restore them though only the locale is in the clipboard and it appears each call to SetData() overwrites the last. (by the way SetDataObject doesn't seem to be the inverse of GetDataObject so I can't just use that)
Any ideas how I can store clipboard state and restore it later?
[STAThread]
static void Main(string[] args)
{
//Store the old clipboard data
Dictionary<string, object> clipboardCache = new Dictionary<string, object>();
IDataObject clipboardData = Clipboard.GetDataObject();
foreach (string format in clipboardData.GetFormats())
{
clipboardCache.Add(format, clipboardData.GetData(format));
}
Clipboard.SetText("Hello world!");
string value = Clipboard.GetText();
Console.WriteLine(value);
//Clear the clipboard again and restore old data
Clipboard.Clear();
foreach (KeyValuePair<string, object> valuePair in clipboardCache)
{
Clipboard.SetData(valuePair.Key, valuePair.Value);
Thread.Sleep(100);
}
Console.ReadLine();
}