Oddity with clipboard access

I am trying to write a small application that should use the clipboard for some functions. Since I do not want to overwrite the user data currently on the clipboard, I decided to save it in memory, do my work and then write it back. The code below is a console application that is an example of the barebones of what I'm trying to do.

The problem I am facing is a state recovery. If I copy something to the clipboard from Visual Studio before running the application, there are six objects in the clipboard (different string formats and locale) that will all be cached. As soon as I restored them, although only the locale is on the clipboard, it seems that every call to SetData () overwrites the last one. (by the way, SetDataObject doesn't seem to be the reverse of GetDataObject, so I can't just use it)

Any ideas how I can save the state of the clipboard 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();
    }
+5
source share
2 answers

Windows . (, RTF, Text, HTML). , , :

//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();
+5
, . ClipX, . , , , ClipX. Clipboard.GetDataObject() . , :
foreach (string format in clipboardData.GetFormats())
{
    clipboardCache.Add(format, clipboardData.GetData(format));
}

ClipX ,

IDataObject clipboardData = Clipboard.GetDataObject();

,

foreach (KeyValuePair<string, object> valuePair in clipboardCache)
{
    Clipboard.SetData(valuePair.Key, valuePair.Value);
    Thread.Sleep(100);
}

, .

-, Clipboard.SetData(format,object) - , . , . .

+1

All Articles