다음을 통해 공유


클립보드에서 데이터를 검색하는 방법

Clipboard 클래스는 Windows 운영 체제 클립보드 기능과 상호 작용하는 데 사용할 수 있는 메서드를 제공합니다. 많은 애플리케이션이 클립보드를 데이터의 임시 리포지토리로 사용합니다. 예를 들어, 워드 프로세서는 클립보드를 잘라낸 후 붙여넣기 작업 중 사용합니다. 또한 클립보드는 한 애플리케이션에서 다른 애플리케이션으로 정보를 전송하는 경우에도 유용합니다.

비고

모든 Windows 기반 애플리케이션은 시스템 클립보드를 공유합니다. 따라서, 다른 애플리케이션으로 전환할 때 내용은 변경될 수 있습니다.

Clipboard 클래스는 STA(단일 스레드 아파트) 모드로 설정된 스레드에서만 사용될 수 있습니다. 이 클래스를 사용하려면 Main 메서드가 STAThreadAttribute 특성으로 표시되었는지 확인하세요.

일부 애플리케이션은 여러 형식의 클립보드에 데이터를 저장하여 잠재적으로 그 데이터를 사용할 수 있는 다른 애플리케이션 수를 증가시킵니다. 클립보드 형식은 형식을 식별하는 문자열입니다. 식별된 형식을 사용하는 애플리케이션은 클립보드에서 연관된 데이터를 검색할 수 있습니다. DataFormats 클래스는 사용자의 사용에 맞게 미리 정의된 형식 이름을 제공합니다. 또한 사용자 자신의 형식 이름을 사용하거나 개체의 유형을 개체의 형식으로 사용할 수 있습니다. 클립보드에 데이터를 추가하는 방법에 대한 자세한 내용은 클립보드에 데이터를 추가하는 방법을 참조하세요.

클립보드에 특정 형식의 데이터가 포함되어 있는지 확인하려면 Contains 메서드 중 하나를 사용합니다. 클립보드에서 데이터를 검색하려면 Get 메서드 또는 메서드 중 TryGetData 하나를 사용하여 사용자 지정 형식을 지정합니다.

비고

.NET Framework에서는 TryGetData 대신 GetData 메서드를 사용하며, GetDataObject 메서드는 일반적으로 다양한 형식의 시나리오에 사용됩니다.

단일 형식으로 검색

GetAudioStream, GetFileDropList, GetImage 또는 GetText 메서드를 사용합니다. 선택적으로, 해당 ContainsFormat 메서드를 먼저 사용하여 데이터를 특정 형식으로 사용할 수 있는지 여부를 확인합니다.

사용자 지정 데이터 형식의 경우, 더 이상 권장되지 않는 GetData 메서드 대신 TryGetData 메서드를 사용하십시오. 이 메서드는 대부분의 경우 GetData 데이터를 성공적으로 반환하지만, 역직렬화가 필요하고 BinaryFormatter 이(가) 사용되지 않는 경우에는 BinaryFormatter 필요함을 나타내는 NotSupportedException 인스턴스를 반환합니다. 사용자 지정 데이터 형식의 경우 형식 안전성을 높이고 종속성을 방지하기 SetDataAsJson<T>() 위해 JSON 기반 메서드(TryGetData<T>()BinaryFormatter)를 사용하는 것이 좋습니다.

비고

.NET Framework에서 이러한 동일한 GetFormat 메서드를 사용할 수 있지만 사용자 지정 형식 대신 GetData 사용합니다TryGetData.

// 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

사용자 지정 형식으로 검색

사용자 지정 형식 이름으로 GetData 메서드를 사용합니다. 이 메서드는 최신 .NET 버전에서 사용되지 않는 GetData 메서드를 대체합니다.

이 메서드와 함께 미리 정의된 형식 이름을 사용할 수도 있습니다. 자세한 내용은 DataFormats를 참조하세요.

중요합니다

.NET 10 이상 SetData 에서는 serialization에 필요한 BinaryFormatter 형식에서 더 이상 작동하지 않습니다. GetData 메서드는 대부분의 경우 데이터를 성공적으로 반환하지만, BinaryFormatter이 역직렬화에 필요하고 활성화되지 않은 경우, NotSupportedException 인스턴스를 반환하여 BinaryFormatter가 필요함을 나타냅니다. 아래 예제에서는 다른 애플리케이션 또는 이전 .NET 버전에서 설정되었을 수 있는 데이터를 검색하는 방법을 보여 줍니다.

비고

.NET Framework에서는 TryGetData 대신 GetData 메서드를 사용하며, SetData를 통한 개체 직렬화가 완전히 지원됩니다.

// 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

Customer 이전 코드 조각에 사용된 클래스:

[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

여러 형식으로 검색

GetDataObject 메서드를 사용하여 IDataObject을(를) 획득한 후, TryGetData를 사용하여 특정 형식으로 데이터를 검색하십시오.

이 방법은 최신의 안전한 API를 사용하기 때문에 최신 .NET 애플리케이션에 권장됩니다.

비고

.NET Framework에서는 일반적으로 GetDataObject 메서드를 사용하고 반환된 IDataObject의 메서드 GetData를 직접 사용하며, 최신 방법인 TryGetData를 사용하지 않습니다.

// 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

참고하십시오