QuickStart: Clipboard basics (XAML)

[This article is for Windows 8.x and Windows Phone 8.x developers writing Windows Runtime apps. If you’re developing for Windows 10, see the latest documentation]

The best apps give users as much control over their data as possible. One method of control that users expect is clipboard operations. These operations enable users to cut, copy, and paste data. Clipboard operations can occur within the same app or between two different apps on the same computer. With the clipboard, users can easily put the information they need where they need it.

More than one way to share data

Before we discuss how to add clipboard operations to your app, you should remember that Windows 8 supports several different ways of moving data. We provide an overview of these methods in Sharing and exchanging data. One of these ways, sharing, has a lot in common with the clipboard. From a developer perspective, both sharing and clipboard operations use the same Windows namespace, Windows.ApplicationModel.DataTransfer. Both also require that your app collect the data that a user selects. (We often refer to this as packaging, because you use the DataPackage class to accomplish this.) From a user's perspective, the clipboard is the "classic" way of moving data around.

As a developer, remember that while sharing and clipboard operations are very similar, they do have key differences. With sharing, the focus is on the app or service that the user selects. With the clipboard, the focus is more on the data. Most importantly, clipboard operations are the only way to exchange data between a desktop app and a Windows Store app. Desktop apps don't support sharing.

For more information about the differences between sharing and clipboard operations, see Sharing and exchanging data.

Built-in clipboard support

In many cases, you do not need to write code to support clipboard operations. Many of the controls that you can use to create your Windows Store app already support clipboard operations. For more information about which controls are available, see Adding controls and content.

Before you begin

Adding support for clipboard operations to your app is pretty straightforward. First, you should take a look at Guidelines and checklist for clipboard commands. There, you'll find a lot of information that can help you create the best user experience for clipboard operations, as well as a few thoughts that can help you make the most of your code.

Next, you need to consider what types of data formats you want to support. In Windows 8, there are two categories of formats: standard and custom. Currently, standard formats include:

  • Text
  • HTML
  • URI
  • Bitmaps
  • StorageItems
  • RTF

To see an example of clipboard operations that use these data formats, see our code sample. You might also want to look at the reference topic, StandardDataFormats, which you use to specify the types of formats that your app supports.

Custom data formats, as the name implies, refers to formats for data that doesn't fit into one of the standard formats. Often, these formats correspond to logical collections of data—such as an address or an event. To support custom formats, we strongly encourage you to use one of the many schemas specified at schema.org. Using commonly known data formats, such as these schemas, helps to ensure that the app that receives the clipboard data knows what to do with it.

Getting started

Supporting clipboard operations usually has two parts: copy (or cut), and paste. Let's look at how to handle copy and cut operations first. First, make sure your app has the appropriate references. If you're using a Microsoft Visual Studio template, these references are added as soon as you create a new project. If you're not using Visual Studio, make sure your app has access to the Windows.ApplicationModel.DataTransfer namespace.

using Windows.ApplicationModel.DataTransfer;

After your project is set up, you need an instance of the DataPackage object. This object contains both the data the user wants to copy and any properties (such as a description) that you want to include.

DataPackage dataPackage = new DataPackage();

Copy and cut

At this point, you are ready to specify the clipboard operation that you want to perform. These operations are available using the DataPackageOperation enumeration. Here's what to do for copy operations:

dataPackage.RequestedOperation = DataPackageOperation.Copy;

And here's what to do for cut operations (also referred to as move operations):

dataPackage.RequestedOperation = DataPackageOperation.Move;

At this point, you can add the data that a user has selected to the DataPackage object. If this data is supported by the DataPackage class, you can use one of the corresponding methods in the DataPackage object. For example, here's how to add text:

dataPackage.SetText("Hello World!");

Here's how to add HTML with embedded images:

string htmlFormat = HtmlFormatHelper.CreateHtmlFormat(this.htmlFragment);
var dataPackage = new DataPackage();
dataPackage.SetHtmlFormat(htmlFormat);

// Populate resourceMap with StreamReference objects corresponding to local 
// image files embedded in HTML.
var imgUri = new Uri(imgSrc);
var imgRef = RandomAccessStreamReference.CreateFromUri(imgUri);
dataPackage.ResourceMap[imgSrc] = imgRef;

To see examples of how to add other formats to a DataPackage, see the clipboard sample in the code gallery. And remember, you can add more than one format to a DataPackage.

The last thing you need to do is add the DataPackage to the clipboard. You can do this by calling the static Clipboard.SetContent method.

Clipboard.SetContent(dataPackage);

Paste

To get the contents of the clipboard, call the static Clipboard.GetContent method. This method returns a DataPackageView that contains the content. This object is almost identical to a DataPackage object, except that its contents are read-only. With that object, you can use either the AvailableFormats or the Contains method to identify what formats are available. Then, you can call the corresponding DataPackageView method to get the data. For example, here's how you can get the text stored in the clipboard:

DataPackageView dataPackageView = Clipboard.GetContent();
if (dataPackageView.Contains(StandardDataFormats.Text))
{
    String text = await dataPackageView.GetTextAsync();

    // To output the text from this example, you need a TextBlock control
    // with a name of "TextOutput".
    TextOutput.Text = "Clipboard now contains: " + text;
}

The following example shows how to get HTML stored in the clipboard.

Be aware that HTML from another app is not trusted and you shouldn't display it unless you're sure the HTML doesn't have any dynamic content. Use the DataTransfer.HtmlFormatHelper.GetStaticFragment method to get shared HTML content without any dynamic elements such as script tags.

var dataPackageView = Clipboard.GetContent();
if (dataPackageView.Contains(StandardDataFormats.Html))
{
    string htmlFormat = null;
    try
    {
        htmlFormat = await dataPackageView.GetHtmlFormatAsync();
    }
    catch (Exception ex)
    {
        rootPage.NotifyUser("Error retrieving HTML format from Clipboard: " + ex.Message, NotifyType.ErrorMessage);
    }

    if (htmlFormat != null)
    {
        string htmlFragment = HtmlFormatHelper.GetStaticFragment(htmlFormat);
        OutputHtml.NavigateToString("Html:<br/ > " + htmlFragment);
    }
}
else
{
    OutputHtml.NavigateToString("Html:<br/ > HTML format is not available in clipboard");
}

Tracking changes to the clipboard

In addition to copy and paste commands, you might also find it helpful to add an event handler so that your app knows when the content of the clipboard changes. You can do this by handling the clipboard's ContentChanged event.

First, add a routed event handler for the Clipboard.ContentChanged event.

Clipboard.ContentChanged += new EventHandler<object>(this.TrackClipboardChanges_EventHandler);

Then implement the event handler method.

private async void TrackClipboardChanges_EventHandler(object sender, object e)
{
    DataPackageView dataPackageView = Clipboard.GetContent();
    if (dataPackageView.Contains(StandardDataFormats.Text))
    {
        String text = await dataPackageView.GetTextAsync();

        // To output the text from this example, you need a TextBlock control
        // with a name of "TextOutput".
        TextOutput.Text = "Clipboard now contains: " + text;
    }
}

With this handler in place, your app is notified when the content of the clipboard changes.

Next steps

By now, you should have a basic understanding of how to add clipboard support to your app. If you haven't done so already, we recommend that you review our Guidelines and checklist for clipboard commands, so you can create the best user experience possible. Also, download our sample from the code gallery to see a variety of examples of how to use the clipboard.