0

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?

zhulien
  • 5,145
  • 3
  • 22
  • 36
Mark Roworth
  • 409
  • 2
  • 15

1 Answers1

0

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);
PVA
  • 24
  • 2
  • Thanks for your help. Given that what I'm trying to store is an instance of a class, what should I supply to `DataFormats.GetFormat`? It appears to take an int or a string. – Mark Roworth Jun 28 '21 at 19:40
  • It's name of your format. In my example it's string "myData". – PVA Jun 28 '21 at 20:36