Wednesday, July 7, 2010

Saving to clipboard using Actionscript 3

Flash and Flex application developers often need to make a button that would save a piece of text to the user's clipboard, like it is shown in the example:


Here is the code:
import flash.desktop.Clipboard;
import flash.desktop.ClipboardFormats;
import fl.controls.Button;

var myText:TextField = new TextField
myText.type = "input"
myText.text = "Enter text here!";
myText.border=true
myText.width=280
myText.height=80
myText.x=myText.y=10
addChild(myText);

var button:Button = new Button();
button.x=10
button.y=100
button.width=280
button.label="Copy to clipboard"
addChild(button);

button.addEventListener(MouseEvent.CLICK, copyText);

function copyText(MouseEvent){
Clipboard.generalClipboard.clear();
Clipboard.generalClipboard.setData(ClipboardFormats.TEXT_FORMAT, myText.text, false);
}

Most of the code is there to create the text field and the button, the whole clipboard code only consists of 2 lines:

Clipboard.generalClipboard.clear();
Clipboard.generalClipboard.setData(ClipboardFormats.TEXT_FORMAT, myText.text, false);

The first line first erases the previous clipboard data, and the second line adds what we need to copy.

Note, that all clipboard events must be called by the user, for example through a button or a mouse click.

No comments:

Post a Comment