次の方法で共有


クリップボードからデータを取得する方法

Clipboard クラスには、Windows オペレーティング システムのクリップボード機能を操作するために使用できるメソッドが用意されています。 多くのアプリケーションでは、クリップボードをデータの一時リポジトリとして使用します。 たとえば、ワード プロセッサでは、切り取りと貼り付けの操作中にクリップボードが使用されます。 クリップボードは、あるアプリケーションから別のアプリケーションに情報を転送する場合にも役立ちます。

すべての Windows ベースのアプリケーションは、システム クリップボードを共有します。 そのため、別のアプリケーションに切り替えると内容が変更される場合があります。

Clipboard クラスは、単一スレッド アパートメント (STA) モードに設定されたスレッドでのみ使用できます。 このクラスを使用するには、 Main メソッドが STAThreadAttribute 属性でマークされていることを確認します。

一部のアプリケーションでは、データを使用できる他のアプリケーションの数を増やすために、複数の形式でクリップボードにデータを格納します。 クリップボード形式は、形式を識別する文字列です。 識別された形式を使用するアプリケーションは、クリップボードに関連付けられているデータを取得できます。 DataFormats クラスには、使用するための定義済みの形式名が用意されています。 独自の形式名を使用したり、オブジェクトの型をその形式として使用したりすることもできます。 クリップボードにデータを追加する方法については、「クリップボード にデータを追加する方法」を参照してください

クリップボードに特定の形式のデータが含まれているかどうかを確認するには、 ContainsFormat メソッドのいずれかを使用します。 クリップボードからデータを取得するには、カスタム形式の GetFormat メソッドまたは TryGetData メソッドのいずれかを使用します。

.NET Framework では、GetDataの代わりに TryGetData メソッドを使用します。GetDataObject メソッドは、複数の形式のシナリオでよく使用されます。

単一形式で取得する

GetAudioStreamGetFileDropListGetImage、またはGetTextメソッドを使用します。 必要に応じて、対応する ContainsFormat メソッドを最初に使用して、データが特定の形式で使用できるかどうかを判断します。

カスタム データ形式の場合は、古いTryGetData メソッドではなく、GetData メソッドを使用します。 GetData メソッドはほとんどの場合、データを正常に返しますが、逆シリアル化にBinaryFormatterが必要であり、有効になっていない場合は、NotSupportedExceptionが必要であることを示すBinaryFormatter インスタンスが返されます。 カスタム データ形式の場合は、JSON ベースのメソッド (SetDataAsJson<T>()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

カスタム形式で取得する

TryGetData メソッドをカスタム書式名と共に使用します。 このメソッドは、.NET の最新バージョンの古い GetData メソッドに置き換えられます。

このメソッドでは、定義済みの形式名を使用することもできます。 詳細については、DataFormatsを参照してください。

Important

.NET 10 以降では、 SetData シリアル化に BinaryFormatter を必要とする型では機能しなくなりました。 GetData メソッドはほとんどの場合、データを正常に返しますが、逆シリアル化にBinaryFormatterが必要であり、有効になっていない場合は、NotSupportedExceptionが必要であることを示すBinaryFormatter インスタンスが返されます。 次の例は、他のアプリケーションまたは以前の .NET バージョンによって設定された可能性があるデータを取得する方法を示しています。

.NET Framework では、GetDataではなく TryGetData メソッドを使用します。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を使用して特定の形式のデータを取得します。

最新の .NET アプリケーションでは、より新しく安全な API を使用しているため、このアプローチをお勧めします。

.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

こちらも参照ください