Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strangeness with clipboard access

Tags:

c#

clipboard

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();
    }
like image 845
Martin Harris Avatar asked Sep 03 '09 16:09

Martin Harris


1 Answers

The windows clipboard only has one object in it at a time. But there are multiple formats available (e.g. RTF, Text, HTML) from that one object. I think you are making it too complicated and your code should be something like this:

//Store the old clipboard data
IDataObject clipboardData = Clipboard.GetDataObject();

Clipboard.SetText("Hello world!");

string value = Clipboard.GetText();
Console.WriteLine(value);

//Clear the clipboard again and restore old data
Clipboard.Clear();
Clipboard.SetDataObject(clipboardData);

Console.ReadLine();
like image 125
Rosco Avatar answered Oct 19 '22 18:10

Rosco