Search code examples
c#clipboardcopy-pasteidataobject

C# Clipboard and DataObject not behaving as expected


I'm trying to use the Clipboard to store selected objects in a program I've written, for the purposes of copy and paste (obviously). My copy code is:

DataObject oWrapper;

Clipboard.Clear();
oWrapper = new DataObject();
oWrapper.SetData(typeof(FormDesignerControls), this.SelectedControls.Clone());
Clipboard.SetDataObject(oWrapper, false);

And my paste code, so far, is:

DataObject oWrapper;

oWrapper = (DataObject)Clipboard.GetDataObject();
if (oWrapper.GetDataPresent(typeof(FormDesignerControls)))
{
    oFDCs = (FormDesignerControls)oWrapper.GetData(typeof(FormDesignerControls));
}

FormDesignerControls is a collection class which will contain the copied objects.

The copy code appears to work fine. When the paste code runs, the call to oWrapper.GetDataPresent returns true in the if conditional. However, the call to oWrapper.GetData returns null.

Am I missing a trick here?


Solution

  • You should register your type of data:

        private static readonly DataFormats.Format myDataClipboardFormat =
            DataFormats.GetFormat("myData");
    

    Copy:

        MyDataType data = <your object>
        DataObject dataObject = new DataObject(myDataClipboardFormat.Name, data);
        Clipboard.SetDataObject(dataObject);
    

    Paste:

        if (!Clipboard.ContainsData(myDataClipboardFormat.Name))
            return;
        IDataObject dataObject = Clipboard.GetDataObject();
        if (dataObject == null)
            return;
        MyDataTypedata = 
           (MyDataType)dataObject.GetData(myDataClipboardFormat.Name);