In my previous article I showed you how to perform Clipboard operations on an image. Today we are going to see Clipboard operations on HTML content.
In this article I will show you how to perform Clipboard operations such as Copy and Paste of HTML content.
Performing Clipboard operations with HTML content is different from other types of formats such as text or a link as the HTML contents can contains links or images or other formats or may be a reference of other contents.
The following describes copying and pasting HTML content using the Clipboard.
Step 1
Create a Blank application of Windows Store apps using C#/XAML.
Step 2
First you need to add the appropriate namespaces in the MainPage.cs file to create HTML content; they are:
using Windows.ApplicationModel.DataTransfer;
using Windows.Data.Html;
Step 3
Now, I use Use the CreateHtmlFormat method of HtmlFormatHelper class that helps to prepare the HTML content correctly for Clipboard operations.
string htmlFormat = HtmlFormatHelper.CreateHtmlFormat(htmlfragment);
Step 4
Then, create the DataPackage object and add the HTML content to the DataPackage object, as in:
var dataPackage = new DataPackage();
dataPackage.SetHtmlFormat(htmlFormat);
Step 5
Now set the content to the Clipboard by setting the object of the dataPackage to the Clipboard.
Here is the code of copying the Copy the content to the Clipboard:
private void copy_Click_1(object sender, RoutedEventArgs e)
{
// Set the content to DataPackage as html format
string htmlFormat = HtmlFormatHelper.CreateHtmlFormat(htmlfragment);
var dataPackage = new DataPackage();
dataPackage.SetHtmlFormat(htmlFormat);
try
{
// Set the DataPackage to clipboard.
Windows.ApplicationModel.DataTransfer.Clipboard.SetContent(dataPackage);
Output.Text = "HTML formats have been copied to clipboard. ";
}
catch (Exception ex)
{
// Copying data to Clipboard can potentially fail - for example, if another application is holding Clipboard open
Output.Text = "Copying data to Clipboard can potentially fail ";


Join the conversation! Your thoughts help the community grow.