Reputation:
I am struggling with using clipboard to copy / paste object, so I created a very simple example to demonstrate the issue.
What is very frustrating is that the same code was working earlier and stopped recently and I am unable to figure out what is wrong.
Basically, the problem is that dataObject.GetData() always returns null even if dataObject.GetDataPresent() returned true earlier.
I am running on .Net 4.5.
using System;
using System.Windows.Forms;
namespace WindowsFormsApp2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var a = new TestClass();
a.Name = "Test";
a.Index = 1;
a.Live = true;
IDataObject dataObj = new DataObject();
// Method 1 : Not working
//dataObj.SetData(a);
// Method 2 : also not working
DataFormats.Format format = DataFormats.GetFormat(a.GetType().FullName);
dataObj.SetData(format.Name, false, a);
Clipboard.SetDataObject(dataObj, false);
}
private void button2_Click(object sender, EventArgs e)
{
IDataObject dataObject = Clipboard.GetDataObject();
// Method 1 : Not working
//if (dataObject.GetDataPresent(typeof(TestClass)))
//{
// // Issue => retrievedObj is ALWAYS null
// var retrievedObj = dataObject.GetData(typeof(TestClass));
//}
// Method 2 : also not working
if (dataObject.GetDataPresent(typeof(TestClass).FullName))
{
// Issue => retrievedObj is ALWAYS null
var retrievedObj = dataObject.GetData(typeof(TestClass).FullName);
}
}
}
public class TestClass
{
public string Name;
public int Index;
public bool Live;
}
}
Any ideas please ?
Upvotes: 0
Views: 1648
Reputation:
I am answering my own question to share my experience.
To keep a long story short, in the original code I wanted to copy / paste an object that was referencing an type (XmlFont, a wrapper type I created to allow serialization of Font type) which was not explicitly marked with Serializable attribute. The funny part though, is that this object was successfully serialized to / from a file using XmlSerializer, so this part is still unclear for me. But marking the XmlFont type as Serializable instantly solved the problem.
Upvotes: 1