Programmatic Clipboard Access in Silverlight 4



Introduction

In Silverlight 4, Microsoft has provided accessing clipboard data programmatically. In this article we will see how it works.

Creating Silverlight Application

Fire up Visual Studio 2010 and Create a new Silverlight Application, name it as ClipboardSample.

ClipBoard1.gif

If you are thinking you can access everything out of clipboard, it's not possible yet. Only the Text content of the clipboard can be accessed.

Let's see what is there in the Clipboard class in the Metadata.

ClipBoard2.gif

As you see in above, we have the Clipboard with 3 methods such as ContainsText(), SetText() and GetText().

In the sample application we will see how we can use the above.

ClipBoard3.gif

The above is the sample UI design which contains a Source TextBox, a Target TextBox and 3 Buttons for Clipboard functions.

Let's add the code for Copy and Cut Buttons Click events.

ClipBoard4.gif

In the above code display, you can see the Clipboard method SetText() in action which takes a string as parameter.

The trick for Cut is just make the selected Text to an empty string.

ClipBoard5.gif

Now let's add code for Paste Button Click event.

In the above code display, you can see the ContainsText() method which returns true or false if Clipboard contains Text.

And finally, we can get the Text out of Clipboard using the method GetText().

Let's run the application and test with various Clipboard data.

ClipBoard6.gif

Now the Textbox has a selection and we can perform either of the operation, Cut or Copy.

And while Pasting it would be pasted to the Target TextBox.

ClipBoard7.gif

When you do access Clipboard programmatically, Silverlight asks you to allow or not. Of course we allow, so press yes. You can check the "Remember my answer" checkbox if you don't want to see this dialog again and again you perform Clipboard.

Now let's create a TextBox in Desktop, and add some Text to it.

ClipBoard8.gif

And we will succeed pasting in our target textbox.

Now, let's copy something else. Let's copy the Text file we just created and try to paste it.

ClipBoard9.gif

You will not get any data other than Text Data. Yes, that is the limitation.

That's it. Hope this article helps.


Similar Articles