Edit

Share via


How to retrieve data from the Clipboard

The Clipboard class provides methods that you can use to interact with the Windows operating system Clipboard feature. Many applications use the Clipboard as a temporary repository for data. For example, word processors use the Clipboard during cut-and-paste operations. The Clipboard is also useful for transferring information from one application to another.

Note

All Windows-based applications share the system Clipboard. Therefore, the contents are subject to change when you switch to another application.

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.

Some applications store data on the Clipboard in multiple formats to increase the number of other applications that can potentially use the data. A Clipboard format is a string that identifies the format. An application that uses the identified format can retrieve the associated data on the Clipboard. The DataFormats class provides predefined format names for your use. You can also use your own format names or use an object's type as its format. For information about adding data to the Clipboard, see How to add data to the Clipboard.

To determine whether the Clipboard contains data in a particular format, use one of the ContainsFormat methods. To retrieve data from the Clipboard, use one of the GetFormat methods or the TryGetData method for custom formats.

Note

In .NET Framework, you use the GetData method instead of TryGetData, and the GetDataObject method is commonly used for multiple format scenarios.

Retrieve in single format

Use the GetAudioStream, GetFileDropList, GetImage, or GetText method. Optionally, use the corresponding ContainsFormat methods first to determine whether data is available in a particular format.

For custom data formats, use the TryGetData method instead of the obsoleted GetData method. The GetData method returns data successfully in most cases, but when BinaryFormatter is required for deserialization and isn't enabled, it returns a NotSupportedException instance that indicates BinaryFormatter is needed. For custom data formats, it's recommended to use the JSON-based methods (SetDataAsJson<T>() and TryGetData<T>()) for better type safety and to avoid BinaryFormatter dependencies.

Note

In .NET Framework, these same GetFormat methods are available, but you use GetData instead of TryGetData for custom formats.

// Demonstrates TryGetData methods for common formats.
// These methods are preferred over the older Get* methods.
public Stream? SwapClipboardAudio(Stream replacementAudioStream)
{
    Stream? returnAudioStream = null;
    if (Clipboard.ContainsAudio())
    {
        returnAudioStream = Clipboard.GetAudioStream();
        Clipboard.SetAudio(replacementAudioStream);
    }
    return returnAudioStream;
}

// Demonstrates TryGetData for file drop lists
public StringCollection? SwapClipboardFileDropList(StringCollection replacementList)
{
    StringCollection? returnList = null;
    if (Clipboard.ContainsFileDropList())
    {
        returnList = Clipboard.GetFileDropList();
        Clipboard.SetFileDropList(replacementList);
    }
    return returnList;
}

// Demonstrates TryGetData for images
public Image? SwapClipboardImage(Image replacementImage)
{
    Image? returnImage = null;
    if (Clipboard.ContainsImage())
    {
        returnImage = Clipboard.GetImage();
        Clipboard.SetImage(replacementImage);
    }
    return returnImage;
}

// Demonstrates TryGetData for text in HTML format
public string? SwapClipboardHtmlText(string replacementHtmlText)
{
    string? returnHtmlText = null;
    if (Clipboard.ContainsText(TextDataFormat.Html))
    {
        returnHtmlText = Clipboard.GetText(TextDataFormat.Html);
        Clipboard.SetText(replacementHtmlText, TextDataFormat.Html);
    }
    return returnHtmlText;
}

// Example of using TryGetData for custom string-based data
public string? GetCustomStringData(string format)
{
    if (Clipboard.TryGetData(format, out object? data))
    {
        return data as string;
    }
    return null;
}
' Demonstrates TryGetData methods for common formats.
' These methods are preferred over the older Get* methods.
Public Function SwapClipboardAudio(ByVal replacementAudioStream As System.IO.Stream) As System.IO.Stream

    Dim returnAudioStream As System.IO.Stream = Nothing

    If Clipboard.ContainsAudio() Then
        returnAudioStream = Clipboard.GetAudioStream()
        Clipboard.SetAudio(replacementAudioStream)
    End If

    Return returnAudioStream

End Function

' Demonstrates TryGetData for file drop lists
Public Function SwapClipboardFileDropList(ByVal replacementList As StringCollection) As StringCollection

    Dim returnList As StringCollection = Nothing

    If Clipboard.ContainsFileDropList() Then
        returnList = Clipboard.GetFileDropList()
        Clipboard.SetFileDropList(replacementList)
    End If

    Return returnList

End Function

' Demonstrates TryGetData for images
Public Function SwapClipboardImage(ByVal replacementImage As Image) As Image

    Dim returnImage As Image = Nothing

    If Clipboard.ContainsImage() Then
        returnImage = Clipboard.GetImage()
        Clipboard.SetImage(replacementImage)
    End If

    Return returnImage

End Function

' Demonstrates TryGetData for text in HTML format
Public Function SwapClipboardHtmlText(ByVal replacementHtmlText As String) As String

    Dim returnHtmlText As String = Nothing

    If Clipboard.ContainsText(TextDataFormat.Html) Then
        returnHtmlText = Clipboard.GetText(TextDataFormat.Html)
        Clipboard.SetText(replacementHtmlText, TextDataFormat.Html)
    End If

    Return returnHtmlText

End Function

' Example of using TryGetData for custom string-based data
Public Function GetCustomStringData(ByVal format As String) As String

    Dim data As Object = Nothing
    If Clipboard.TryGetData(format, data) Then
        Return TryCast(data, String)
    End If

    Return Nothing

End Function

Retrieve in custom format

Use the TryGetData method with a custom format name. This method replaces the obsoleted GetData method in modern .NET versions.

You can also use predefined format names with this method. For more information, see DataFormats.

Important

In .NET 10 and later, SetData no longer works with types that require BinaryFormatter for serialization. The GetData method returns data successfully in most cases, but when BinaryFormatter is required for deserialization and isn't enabled, it returns a NotSupportedException instance that indicates BinaryFormatter is needed. The examples below show how to retrieve data that may have been set by other applications or earlier .NET versions.

Note

In .NET Framework, you use the GetData method instead of TryGetData, and object serialization through SetData is fully supported.

// Demonstrates TryGetData using a custom format name and a business object.
// Note: In .NET 10, SetData for objects is no longer supported,
// so this example shows how to retrieve data that might have been
// set by other applications or earlier .NET versions.
public Customer? TestCustomFormat
{
    get
    {
        // For demonstration, we'll use string data instead of objects
        // since SetData for objects is no longer supported in .NET 10
        if (Clipboard.TryGetData("CustomerFormat", out object? data))
        {
            return data as Customer;
        }
        return null;
    }
}
' Demonstrates TryGetData using a custom format name and a business object.
' Note: In .NET 10, SetData for objects is no longer supported,
' so this example shows how to retrieve data that might have been
' set by other applications or earlier .NET versions.
Public ReadOnly Property TestCustomFormat() As Customer
    Get
        Dim data As Object = Nothing
        ' For demonstration, we'll use string data instead of objects
        ' since SetData for objects is no longer supported in .NET 10
        If Clipboard.TryGetData("CustomerFormat", data) Then
            Return TryCast(data, Customer)
        End If
        Return Nothing
    End Get
End Property

The Customer class used in the previous snippet:

[Serializable]
public class Customer
{
    private string nameValue = string.Empty;
    public Customer(string name)
    {
        nameValue = name;
    }
    public string Name
    {
        get { return nameValue; }
        set { nameValue = value; }
    }
}
<Serializable()>
Public Class Customer

    Private nameValue As String = String.Empty

    Public Sub New(ByVal name As String)
        nameValue = name
    End Sub

    Public Property Name() As String
        Get
            Return nameValue
        End Get
        Set(ByVal value As String)
            nameValue = value
        End Set
    End Property

End Class

Retrieve in multiple formats

Use the GetDataObject method to get an IDataObject, then use TryGetData to retrieve data in specific formats.

This approach is recommended for modern .NET applications as it uses the newer, safer APIs.

Note

In .NET Framework, you typically use the GetDataObject method and work directly with the returned IDataObject, using its methods like GetData instead of the newer TryGetData approach.

// Demonstrates how to retrieve data from the Clipboard in multiple formats
// using TryGetData instead of the obsoleted GetData method.
public void TestClipboardMultipleFormats()
{
    IDataObject? dataObject = Clipboard.GetDataObject();
    
    if (dataObject != null)
    {
        // Check for custom format
        if (dataObject.GetDataPresent("CustomFormat"))
        {
            if (Clipboard.TryGetData("CustomFormat", out object? customData))
            {
                if (customData is ListViewItem item)
                {
                    MessageBox.Show(item.Text);
                }
                else if (customData is string stringData)
                {
                    MessageBox.Show(stringData);
                }
            }
        }

        // Check for Customer type - note that object serialization
        // through SetData is no longer supported in .NET 10
        if (dataObject.GetDataPresent(typeof(Customer)))
        {
            if (Clipboard.TryGetData(typeof(Customer).FullName!, out object? customerData))
            {
                if (customerData is Customer customer)
                {
                    MessageBox.Show(customer.Name);
                }
            }
        }

        // For modern .NET 10 applications, prefer using standard formats
        if (Clipboard.ContainsText())
        {
            string text = Clipboard.GetText();
            MessageBox.Show($"Text data: {text}");
        }
    }
}
' Demonstrates how to retrieve data from the Clipboard in multiple formats
' using TryGetData instead of the obsoleted GetData method.
Public Sub TestClipboardMultipleFormats()

    Dim dataObject As IDataObject = Clipboard.GetDataObject()

    If dataObject IsNot Nothing Then

        ' Check for custom format
        If dataObject.GetDataPresent("CustomFormat") Then

            Dim customData As Object = Nothing
            If Clipboard.TryGetData("CustomFormat", customData) Then

                Dim item As ListViewItem = TryCast(customData, ListViewItem)
                If item IsNot Nothing Then
                    MessageBox.Show(item.Text)
                ElseIf TypeOf customData Is String Then
                    MessageBox.Show(CStr(customData))
                End If

            End If

        End If

        ' Check for Customer type - note that object serialization
        ' through SetData is no longer supported in .NET 10
        If dataObject.GetDataPresent(GetType(Customer)) Then

            Dim customerData As Object = Nothing
            If Clipboard.TryGetData(GetType(Customer).FullName, customerData) Then

                Dim customer As Customer = TryCast(customerData, Customer)
                If customer IsNot Nothing Then
                    MessageBox.Show(customer.Name)
                End If

            End If

        End If

        ' For modern .NET 10 applications, prefer using standard formats
        If Clipboard.ContainsText() Then
            Dim text As String = Clipboard.GetText()
            MessageBox.Show($"Text data: {text}")
        End If

    End If

End Sub
[Serializable]
public class Customer
{
    private string nameValue = string.Empty;
    public Customer(string name)
    {
        nameValue = name;
    }
    public string Name
    {
        get { return nameValue; }
        set { nameValue = value; }
    }
}
<Serializable()>
Public Class Customer

    Private nameValue As String = String.Empty

    Public Sub New(ByVal name As String)
        nameValue = name
    End Sub

    Public Property Name() As String
        Get
            Return nameValue
        End Get
        Set(ByVal value As String)
            nameValue = value
        End Set
    End Property

End Class

See also