Clipboard

Browse sample. Browse the sample

This article describes how you can use the .NET Multi-platform App UI (.NET MAUI) IClipboard interface. With this interface, you can copy and paste text to and from the system clipboard.

The default implementation of the IClipboard interface is available through the Clipboard.Default property. Both the IClipboard interface and Clipboard class are contained in the Microsoft.Maui.ApplicationModel.DataTransfer namespace.

Tip

Access to the clipboard must be done on the main user interface thread. For more information on how to invoke methods on the main user interface thread, see MainThread.

Using Clipboard

Access to the clipboard is limited to string data. You can check if the clipboard contains data, set or clear the data, and read the data. The ClipboardContentChanged event is raised whenever the clipboard data changes.

The following code example demonstrates using a button to set the clipboard data:

private async void SetClipboardButton_Clicked(object sender, EventArgs e) =>
    await Clipboard.Default.SetTextAsync("This text was highlighted in the UI.");

The following code example demonstrates using a button to read the clipboard data. The code first checks if the clipboard has data, read that data, and then uses a null value with SetTextAsync to clear the clipboard:

private async void ReadClipboardButton_Clicked(object sender, EventArgs e)
{
    if (Clipboard.Default.HasText)
    {
        ClipboardOutputLabel.Text = await Clipboard.Default.GetTextAsync();
        await ClearClipboard();
    }
    else
        ClipboardOutputLabel.Text = "Clipboard is empty";
}

private async Task ClearClipboard() =>
    await Clipboard.Default.SetTextAsync(null);

Clear the clipboard

You can clear the clipboard by passing null to the SetTextAsync method, as the following code example demonstrates:

private async Task ClearClipboard() =>
    await Clipboard.Default.SetTextAsync(null);

Detecting clipboard changes

The IClipboard interface provides the ClipboardContentChanged event. When this event is raised, the clipboard content has changed. The following code example adds a handler to the event when the content page is loaded:

private void ContentPage_Loaded(object sender, EventArgs e)
{
    Clipboard.Default.ClipboardContentChanged += Clipboard_ClipboardContentChanged;
}

private async void Clipboard_ClipboardContentChanged(object sender, EventArgs e)
{
    ClipboardOutputLabel.Text = await Clipboard.Default.GetTextAsync();
}