tags:

views:

204

answers:

2

I'm trying to add copy/paste to an application that edits items. Having a copy of the data for a set of selected items, should enable duplicating them or transporting them to another instance of the program. I've tried this:

const string MyClipboardFormat = "MyClipboardFormat"

private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
  XmlDocument xdoc;
  //add data of selected items
  Clipboard.SetData(MyClipboardFormat,xdoc);
}

private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{
  XmlDocument xdoc = Clipboard.GetData(MyClipboardFormat) as XmlDocument;
  if (xdoc == null)
    throw new Exception("Clipboard does not contain MyClipboardFormat");
  //read item data from xdoc
}

I've googled but found only bits about using GetDataObject/SetDataObject, equivalent to what appears to be going on anyway, if I use reflector to look what GetData/SetData does.

Should I register the clipboard format string somewhere?

+1  A: 

You need to register your format. Use DataFormats.GeTFormat(MyClipboardFormat):

Call this method with your own format name to create a new Clipboard format type. If the specified format does not exist, this method will register the name as a Clipboard format with the Windows registry and get a unique format identifier.

Remus Rusanu
Nope, this doesn't help. I'm not even sure what to do with the 'format' returned here. GetData/SetData takes a string as format descriptor.
Stijn Sanders
+1  A: 

I had a similar problem and to get it to work, I had to serialize the object before placing it on the clipboard and unserialize it after my call to Clipboard.GetData()

Der Wolf