user779444 user779444 - 4 months ago 55
C# Question

C# Backing Up And Restoring Clipboard

I have a program that uses clipboard but I want to restore the clipboard to its former state after I am done with it.

This is my code :

IDataObject temp = Clipboard.GetDataObject();

//Some stuff that change Cliboard here
//Some stuff that change Cliboard here


But it if I copy a text, and run this code, I get nothing on notepad.

NOTE : I can't use Clipboard.Contains because I want to preserve the Clipboard EXACLY how it was before, even if the user copied a file.


I cannot confirm whether this will work, but I see no reason why you shouldn't be able to back up the data using the longer approach of actually reading the data and restoring it afterwards.

Read here:

You would do something like (pseudo-code)

var lBackup = new Dictionary<string, object>();
var lDataObject = Clipboard.GetDataObject();
var lFormats = lDataObject.GetFormats(false);
foreach(var lFormat in lFormats)
  lBackup.Add(lFormat, lDataObject.GetData(lFormat, false));

//Set test data

//Would be interesting to check the contents of lDataObject here

//Restore data
foreach(var lFormat in lFormats)
//This might be unnecessary