Windows Phone 8 Development Internals: Phone and Media Services

  • 6/15/2013

The Clipboard API

Windows Phone 8 includes programmatic support for the clipboard, albeit in a constrained manner. You can set text into the system-wide clipboard, but you cannot extract text from it programmatically. This constraint is for security and privacy reasons, and it ensures that the user is always in control of where the clipboard contents might be sent. Figure 5-14 shows the TestClipboard application in the sample code.

This example offers a RichTextBox at the top with a Button below it, and a regular TextBox at the bottom. The RichTextBox is populated with some dummy text. The reason for this choice of controls is that you want to get your text from a control that supports selection of its contents, which the RichTextBox does. You also need to make an editable text control available into which the user can paste; hence, the TextBox. When the user taps the button, you arbitrarily select some or all of the text in the RichTextBox and then set this text into the clipboard by using the static Clipboard.SetText method.

private void copyText_Click(object sender, RoutedEventArgs e)
{
    textSource.SelectAll();
    Clipboard.SetText(textSource.Selection.Text);
}

After this, if and when the user chooses to tap the regular TextBox, the standard phone UI will show the Soft Input Panel (SIP) and include a paste icon, indicating that there is some text in the clipboard. If the user taps this icon, the clipboard contents are pasted into the TextBox. This last operation is outside your control and is handled entirely by the phone platform. Be aware that the clipboard is cleared whenever the phone lock engages.

Figure 5-14

Figure 5-14 A simple clipboard application.