This documentation is archived and is not being maintained.

Retrieving Information from the Clipboard

Visual Studio .NET 2003

A number of applications use the Clipboard as a temporary repository for data. Retrieving data from the Clipboard is done through the IDataObject interface. In this way, data on the Clipboard is stored in a very basic fashion, accessible through a number of different DataFormats, so that the data stored there is available for the greatest variety of uses. For example, a string of text from within a .NET Framework application stored on the Clipboard is available in formats including Text, StringFormat, RTF, and Unicode Text.

To retrieve information from the Clipboard

  1. Drag a TextBox control and a Button control from the Toolbox to your form.
  2. Double-click the Button control to create a Click event handler.

    The Code Editor opens, with the insertion point in the Click event handler.

  3. In the event handler, write code to get the data from the Clipboard using the GetDataObject method. Test whether the data is of an acceptable type using the GetDataPresent method to test which of the DataFormats is being used. Finally, set the Text property of the TextBox control to the string represented in the data using the GetData method.
    Note   The following code sample presupposes the presence of text on the Clipboard. For more information about sending data to the Clipboard, see Placing Data on the Clipboard.
    ' Visual Basic
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    ' Create a new instance of the DataObject interface.
       Dim data As IDataObject = Clipboard.GetDataObject()
    ' If the data is text, then set the text of the 
    ' TextBox to the text in the Clipboard.
       If (data.GetDataPresent(DataFormats.Text)) Then
         TextBox1.Text = data.GetData(DataFormats.Text).ToString()
       End If
    End Sub
    // C#
    private void button1_Click(object sender, System.EventArgs e)
       // Create a new instance of the DataObject interface.
       IDataObject data = Clipboard.GetDataObject();
       // If the data is text, then set the text of the 
       // TextBox to the text in the Clipboard.
       if (data.GetDataPresent(DataFormats.Text))
          textBox1.Text = data.GetData(DataFormats.Text).ToString();

See Also

Placing Data on the Clipboard | Drag-and-Drop Operations and Clipboard Support