Clipboard.GetDataObject Method

Definition

Retrieves the data that is currently on the system Clipboard.

C#
public static System.Windows.Forms.IDataObject GetDataObject ();
C#
public static System.Windows.Forms.IDataObject? GetDataObject ();

Returns

An IDataObject that represents the data currently on the Clipboard, or null if there is no data on the Clipboard.

Exceptions

Data could not be retrieved from the Clipboard. This typically occurs when the Clipboard is being used by another process.

The current thread is not in single-threaded apartment (STA) mode and the MessageLoop property value is true. Add the STAThreadAttribute to your application's Main method.

Examples

The following code example uses Clipboard methods to place data on and retrieve it from the system Clipboard. This code assumes button1, button2, textBox1, and textBox2 have been placed on the form.

The button1_Click method calls SetDataObject to take selected text from the text box and place it on the system Clipboard.

The button2_Click method calls GetDataObject to retrieve data from the system Clipboard. The code uses IDataObject and DataFormats to extract the data returned. The data is displayed in textBox2.

C#
private void button1_Click(object sender, System.EventArgs e) {
    // Takes the selected text from a text box and puts it on the clipboard.
    if(textBox1.SelectedText != "")
       Clipboard.SetDataObject(textBox1.SelectedText);
    else
       textBox2.Text = "No text selected in textBox1";
 }
 
 private void button2_Click(object sender, System.EventArgs e) {
    // Declares an IDataObject to hold the data returned from the clipboard.
    // Retrieves the data from the clipboard.
    IDataObject iData = Clipboard.GetDataObject();
 
    // Determines whether the data is in a format you can use.
    if(iData.GetDataPresent(DataFormats.Text)) {
       // Yes it is, so display it in a text box.
       textBox2.Text = (String)iData.GetData(DataFormats.Text); 
    }
    else {
       // No it is not.
       textBox2.Text = "Could not retrieve data off the clipboard.";
    }
 }

Remarks

Because the data type of the object returned from the Clipboard can vary, this method returns the data in an IDataObject. Then you can use methods of the IDataObject interface to extract the data in its proper data type.

This method attempts to get the data ten times in 100-millisecond intervals, and throws an ExternalException if all attempts are unsuccessful.

Note

The Clipboard class can only be used in threads set to single thread apartment (STA) mode. To use this class, ensure that your Main method is marked with the STAThreadAttribute attribute.

Applies to

Product Versions
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9

See also