Sdílet prostřednictvím


Jak načíst data ze schránky

Třída Clipboard poskytuje metody, které můžete použít k interakci s funkcí Schránka operačního systému Windows. Mnoho aplikací používá schránku jako dočasné úložiště údajů. Například textové procesory používají schránku během operací vystřižení a vložení. Schránka je užitečná také pro přenos informací od jedné aplikace k druhé.

Poznámka:

Všechny aplikace založené na Systému Windows sdílejí systémovou schránku. Obsah se proto může změnit, když přepnete do jiné aplikace.

Třída Clipboard lze použít pouze ve vláknech nastavených na režim jednovláknového apartmentu (STA). Chcete-li použít tuto třídu, ujistěte se, že je vaše metoda Main označena atributem STAThreadAttribute.

Některé aplikace ukládají data do schránky ve více formátech, aby se zvýšil počet dalších aplikací, které by data potenciálně mohly používat. Formát schránky je řetězec, který identifikuje formát. Aplikace, která používá identifikovaný formát, může načíst přidružená data ve Schránce. Třída DataFormats poskytuje předdefinované názvy formátů pro vaše použití. Můžete také použít vlastní názvy formátů nebo jako jeho formát použít typ objektu. Informace o přidávání dat do schránky naleznete v tématu Postup přidání dat do schránky.

Chcete-li zjistit, zda Schránka obsahuje data v určitém formátu, použijte jednu z Contains metod Format. Chcete-li načíst data ze schránky, použijte jednu z metod GetFormat nebo metodu TryGetData pro vlastní formáty.

Poznámka:

V rozhraní .NET Framework použijete GetData místo metody TryGetDataa GetDataObject metoda se běžně používá pro různé scénáře formátu.

Načíst v jediném formátu

Použijte metodu GetAudioStream, GetFileDropList, GetImagenebo GetText. Volitelně můžete nejprve použít odpovídající metody ContainsFormat určit, zda jsou data k dispozici v určitém formátu.

Pro vlastní formáty dat použijte metodu TryGetData místo zastaralé GetData metody. Pokud je BinaryFormatter vyžadována pro deserializaci a není povolena, metoda GetData ve většině případů úspěšně vrací data, ale vrátí instanci NotSupportedException, která označuje, že je potřeba BinaryFormatter. Pro vlastní formáty dat se doporučuje použít metody založené na JSON (SetDataAsJson<T>() a TryGetData<T>()) pro lepší zabezpečení typů a zabránění BinaryFormatter závislostem.

Poznámka:

V rozhraní .NET Framework jsou k dispozici stejné Get metody formátu, ale používáte GetData místo TryGetData pro vlastní formáty.

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

Načtení ve vlastním formátu

Použijte metodu TryGetData s vlastním názvem formátu. Tato metoda nahrazuje zastaralou GetData metodu v moderních verzích .NET.

V této metodě můžete také použít předdefinované názvy formátů. Další informace najdete v tématu DataFormats.

Důležité

V .NET 10 a novějších SetData už nefunguje s typy, které vyžadují BinaryFormatter pro serializaci. Metoda GetData ve většině případů úspěšně vrací data, ale je-li BinaryFormatter vyžadována pro deserializaci a není povolena, vrátí instanci NotSupportedException, která označuje, že je potřeba BinaryFormatter. Následující příklady ukazují, jak načíst data, která mohou být nastavena jinými aplikacemi nebo staršími verzemi .NET.

Poznámka:

V rozhraní .NET Framework použijete metodu GetData namísto TryGetDataa serializace objektů prostřednictvím SetData je plně podporována.

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

Třída Customer použitá v předchozím fragmentu kódu:

[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

Načíst v různých formátech

Použijte metodu GetDataObject k získání IDataObjecta pak použijte TryGetData k načtení dat v konkrétních formátech.

Tento přístup se doporučuje pro moderní aplikace .NET, protože používá novější a bezpečnější rozhraní API.

Poznámka:

V rozhraní .NET Framework obvykle používáte metodu GetDataObject a pracujete přímo s vráceným IDataObject, pomocí jejích metod, jako je GetData, místo novějšího přístupu 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

Viz také