C# 剪贴板和 DataObject 未按预期运行

C# Clipboard and DataObject not behaving as expected

我正在尝试使用 Clipboard 将选定的对象存储在我编写的程序中,以便进行复制和粘贴(显然)。我的复制码是:

DataObject oWrapper;

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

到目前为止,我的粘贴代码是:

DataObject oWrapper;

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

FormDesignerControls 是一个集合 class,它将包含复制的对象。

复制代码似乎工作正常。当粘贴代码运行时,在 if 条件中调用 oWrapper.GetDataPresent returns true。但是,调用 oWrapper.GetData returns null.

我是不是漏掉了什么技巧?

您应该注册您的数据类型:

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

复制:

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

粘贴:

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