Save any Clipboard content and reload it?

114 views Asked by At

I need to use clipboard memory for 1 sec, doing some stuff, and reload the clipboard as original.

I want my cliboard do :

  • "original random text, image, sound or anything else" --> "My Useful Text"
  • "My Useful Text" --> "random text, image, sound or anything else"

But what my clipboard do :

  • "original random text, image, sound or anything else" --> "My Useful Text"
  • "My Useful Text" --> " " [nothing]
using System.Windows.Forms;

public class ExplorerTools 
{
  public void Run()
  {
    // saving the current clipboard
    var oldClipboard = Clipboard.GetDataObject();

    // Doing some stuff with the clipboard
    Clipboard.SetText("My Useful Text");
    System.Threading.Thread.Sleep(400);

    // I want to put back oldClipboard in the clipboard
    Clipboard.SetDataObject(oldClipboard);
  }
}

I don't understand why Clipboard.SetDataObject() cannot retrieve the old value, he just put nothing ='(

1

There are 1 answers

0
nitrateag On BEST ANSWER

Like @Taw said, i can't directly use the IDataObject i get from Clipboard.GetDataObject(). So I have to save every 21 kind of clipboard data and reload it individually myself.

using System.Windows.Forms;

public class ExplorerTools 
{
  public void Run()
  {
    // saving the current clipboard
    string[] arr_format = Clipboard.GetDataObject().GetFormats(false);
    Dictionary<string, object> dic_oldDataClipboard = new Dictionary<string, object>();
    foreach(string format in arr_format)
      dic_oldDataClipboard.Add(format, Clipboard.GetData(format));


    // Doing some stuff with the clipboard
    Clipboard.SetText("My Useful Text");
    System.Threading.Thread.Sleep(400);


    // I want to put back oldClipboard in the clipboard
    foreach(var format_data in dic_oldDataClipboard)
      Clipboard.SetData(format_data.Key, format_data.Value);
  }
}