Copy and paste objects to the clipboard in C#
The only real trick here is to decorate the class that you want to use with the Serializable attribute. That allows the clipboard to serialize and deserialize instances of the class. The following code shows this example's Person class.
[Serializable()]To copy an object to the clipboard, simply call the Clipboard object's SetDataObject method.
class Person
{
public string FirstName;
public string LastName;
}
// Copy a Person to the Clipboard.The following code shows how the program pastes an object from the clipboard.
private void btnCopy_Click(object sender, EventArgs e)
{
Person person = new Person() { FirstName = txtFirstName.Text, LastName = txtLastName.Text };
Clipboard.SetDataObject(person);
}
// Paste the person from the Clipboard.First the code uses the GetDataPresent method to see if the clipboard is holding an object of the correct type. Notice that the object's type name includes its namespace. If there is an object of the right class present, the program uses the Clipboard's GetData method to get it.
private void btnPaste_Click(object sender, EventArgs e)
{
IDataObject data_object = Clipboard.GetDataObject();
if (data_object.GetDataPresent("howto_clipboard_objects.Person"))
{
Person person = (Person)data_object.GetData("howto_clipboard_objects.Person");
txtDropFirstName.Text = person.FirstName;
txtDropLastName.Text = person.LastName;
}
else
{
txtDropFirstName.Clear();
txtDropLastName.Clear();
}
}


Nice tip, I didn't actually know you could do that!
If you have to provide the full name of the class in order to deserialize (which I assume you do as you're including the "howto_clipboard_objects" namespace) then it might perhaps be better to let .NET provide the name rather than a string literal - then you can be happy if you rename the namespace (or indeed the class) as it will continue to "just work"
For example:
Person person = (Person)data_object.GetData(typeof(Person).FullName);
Reply to this
Good idea!
Reply to this