Copy and paste objects to the clipboard in C#

Copy and paste objects to the clipboard

It’s pretty easy to copy and paste objects to the clipboard in C#. The only real trick 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()]
class Person
{
    public string FirstName;
    public string LastName;
}

The following code shows how the program copies a Person object to the clipboard.

// Copy a Person to the Clipboard.
private void btnCopy_Click(object sender, EventArgs e)
{
    Person person = new Person() {
        FirstName = txtFirstName.Text,
        LastName = txtLastName.Text
    };
    Clipboard.SetDataObject(person);
}

This code uses the values in the program’s text boxes to create a new Person object. It then simply calls the Clipboard object’s SetDataObject method.

The following code shows how the program pastes a Person object from the clipboard.

// Paste the person from the Clipboard.
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();
    }
}

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 object’s GetData method to get it. The result has the plain Object type, so the code casts it into a Person object.


Download Example   Follow me on Twitter   RSS feed




This entry was posted in clipboard and tagged , , , , , , , , . Bookmark the permalink.

3 Responses to Copy and paste objects to the clipboard in C#

  1. Richard Moss says:

    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);

  2. Pingback: Copy and paste scribble data in C# - C# HelperC# Helper

Leave a Reply

Your email address will not be published. Required fields are marked *