Saturday, April 16, 2011

Working with clipboard in AIR: Part 3

Today we'll learn how to write, read and delete data from clipboard.

We are already familiar with the method setData(). We simply set the data format and then a value as parameters.

For example:

import flash.desktop.Clipboard;

var myText:String = "This is a string!";

var myClip:Clipboard = Clipboard.generalClipboard;
myClip.setData(ClipboardFormats.TEXT_FORMAT, myText);

If you test that code and after running it open a text editor like Word or Notepad and press CTRL+V (paste what's in your clipboard) you'll paste the string that you've specified in the code.

Now that we know how to set data to the system clipboard, let's see how do we read it.

Reading text is also really simple, use the method getData() for that. You need to specify the clipboard format that you want to read and you may also "cast" the value and tell Flash to read it as a specific type of a variable, for example, String:

var receivedText:String = myClip.getData(ClipboardFormats.TEXT_FORMAT) as String;

Casting is not absolutely necessary, but makes your code more error-proof.

Sometimes you might want to remove data from the users clipboard. In fact, it is always a good thing to clear the clipboard before adding your own data to it, and there are several reasons for that, one of them is the fact that different programs have different ways of reading from clipboard and will sometimes not read data of one format if there is some data of another format in the clipboard.

Anyway, to clear the clipboard, you can use the method clearData(), where you pass the format of the data you want to remove as a parameter:

myClip.clearData(ClipboardFormats.TEXT_FORMAT);

You can also clean the whole clipboard by using the clear() method that requires no parameters:

myClip.clear();

And that's all for now.

Thanks for reading!

Related:

Working with clipboard in AIR: Part 1
Working with clipboard in AIR: Part 2
Working with clipboard in AIR: Part 4
Working with clipboard in AIR: Part 5
Working with clipboard in AIR: Part 6
Working with clipboard in AIR: Part 7
Working with clipboard in AIR: Part 8
Working with clipboard in AIR: Part 9
Working with clipboard in AIR: Part 10

No comments:

Post a Comment