This is not as simple as it might seem initially.
Clipboard data are stored by the system internally in various formats (global memory, IStream, IStorage, file, GDI object).
This is also the reason why the code from the
Clipboard backup in C#[
^] article can crash:
It uses Win32 API calls but does not check the storage type. It assumes global memory data which results in
NULL
pointers when trying to access global memory with a handle that is for example an an
IStream
or a GDI object.
So you have to determine the storage type for each clipboard object and store it together with the format and the raw data. Upon restoring, the same storage types should be used (and must be for GDI objects).
I must confess that I don't know what
IDataObject.GetData Method (String, Boolean) (System.Windows.Forms)[
^] is doing internally. But it returns a
System.Object
type which is probably not able to represent all kinds of data that may be on the clipboard and might not use the same storage method when putting such on the clipboard. But it will handle the different storage methods and use them to read the data and create a
System.Object
.
Even when handling all the above there might be differences in the internal clipboard data because an application must not put data on the clipboard initially but can create the content upon request when the data are retrieved (delay rendering). A clipboard source may also specify a release callback function which can't be stored and re-used by your application when putting the data back.