Windows-task-snippets/tasks/Clipboard-text.md

1.4 KiB

Get or set clipboard text

Gets or sets the current clipboard text.

If the clipboard contains a non-text item (like an image), GetClipboardTextAsync returns an empty string.

using System;
using System.Threading.Tasks;
using Windows.ApplicationModel.DataTransfer;

public static async Task<string> GetClipboardTextAsync()
{
    DataPackageView dataPackage = Clipboard.GetContent();
    return dataPackage.Contains(StandardDataFormats.Text) ? 
        await dataPackage.GetTextAsync() : ""; 
}

public static void SetClipboardText(string text)
{
    var dataPackage = new DataPackage();
    dataPackage.SetText(text);
    Clipboard.SetContent(dataPackage);
}

See also

Clipboard class
DataPackage class
DataPackageView class
?: operator

For more advanced clipboard interactions, including handling non-text objects or firing events when the clipboard contents change, see Copy and paste.