Monday, April 18, 2011

Working with clipboard in AIR: Part 5

Today we will learn about handling the data we want to write to the clipboard.

Most of the time, when we put something in our clipboard, it is written there immediately.

However, there are situations, when its better not to write the data just yet, but only update the clipboard when the user wants to use it and extract the data from the clipboard. This is useful in situations, when the data in your application is regularly being updated, and when you are extracting the data, you only want to take the fresh version of it.

If you need to do this kind of handling for the data, don't use the setData() method, but use setDataHandler() instead. This method also requires you to specify the clipboard format of the data, as well as the function that needs to be called once the user wants to extract the data from the clipboard. The function should return the data you want to send, and it should be passed as the second parameter of setDataHandler().

And example of usage of this method:

import flash.desktop.Clipboard;
import flash.desktop.ClipboardFormats;

var myClip:Clipboard = Clipboard.generalClipboard;

myClip.setDataHandler(ClipboardFormats.TEXT_FORMAT, getDate);

function getDate():String {
return new Date().toString();
}

If you test the code above and then open Notepad or Word or any other program with text fields and try to paste whatever is in your clipboard into the text field - you will paste the date and time of the moment you extract the data from the clipboard, NOT the moment you use setDataHandler().

Note that this method only works once - if you extract from your clipboard one time, the next time you do it, it will be the same value - the handler will not be there anymore and won't track any updates.

Thanks for reading!

Related:

Working with clipboard in AIR: Part 1
Working with clipboard in AIR: Part 2
Working with clipboard in AIR: Part 3
Working with clipboard in AIR: Part 4
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