Copying data to the clipboard in Silverlight

I was recently trying to add the ability for our network operations team to be able to copy alert text from a new Silverlight based tool and discovered much to my surprise that copying text out of Silverlight is not a straightforward process.

I will start off with the “Best” solution I was able to find and I will detail other the other less desirable option below.

Option 1:   Copy it out with JavaScript (Note Non IE browsers require some extra work to make this happen)

Simply build a string that contains what you want to copy into the clipboard and call the JavaScript function.

Sample JavaScript code to place in your aspx/html file:

<head runat="server">

    <script type="text/javascript" language="javascript">

        function CopyToClipBoard(TextToUse)

        {

            window.clipboardData.setData('Text', TextToUse);

        }

    </script>

</head>

Silverlight C# code:

String MyString “Some Data”;

HtmlPage.Window.CreateInstance("CopyToClipboard", MyString);

The Javascript code above only works in IE, however you can find code online to enable javascript to copy to the clipboard in other browsers (See below about why they don’t make it easy).

Option 2: Place all strings you want to be copied into a TextBox. (Works with all browsers)

Using a TextBox gives the user the ability to highlight the text and to simply do a ctrl-c to copy the text into

The only object that I could find that let you select text is the TextBox object. So if you just want to allow the user to highlight and copy (via a ctrl-c) you can put your text in a TextBox object (Set it read only if you don’t want them to be able to edit it).

This solution has doesn’t allow you to format your text as nicely as the user is limited to only selecting only one TextBox at a time.

Why is this not easy to do?

The first thing you need to understand is why they didn’t make it easy for people to copy data to and from the clipboard. The short answer is security. They don’t want a malicious website to be able to copy down or modify what is in the clipboard as it may contain sensitive information. That being said there are many times when it is useful for an application to be able to copy text to the clipboard and I have great hopes that Silverlight 3 will give the end user the option to allow/deny access to the windows clipboard.