

When I started getting a hang of new stuff introduced in AS3, I got to notice that it has done away with a bunch of commands that were available in AS2. One of these missing commands included “Key.isDown” and added too that there were simply no key objects in AS3. Instead it has an alternative process whereby key codes can be accessed by name basically utilizing the keyboard class.
Now lets take a closer look; in AS3 in “Key.isDown” is basically an event handling process which is made out of a two step process
To elaborate the above concept of keyboard event handling Actionscript3 has build in “KeyboardEvent” and “keyboard” class. keypress event can be elaborated as
addEventListener(KeyboardEvent.KEY_UP,keyHandlerfunction)
Or
addEventListener(KeyboardEvent.KEY_down, keyHandlerfunction)
Here KEY_UP and KEY_DOWN are constants for respective key up or key down events. Key down event takes place when a key is pressed and reverse Key up event takes place when a pressed key is released.
keyHandlerfunction function will be executed in response to key up or key down event.
package
{
import flash.display.DisplayObject;
import flash.events.*;
public class Event_Example extends DisplayObject {
private var child: DisplayObject = new DisplayObject ();
// register the listener function
public function Event_Handle_Example()
{
addChild(child);
child.addEventListener(KeyboardEvent.KEY_UP, keyHandlerfunction);
}
// listener funtion
private function keyHandlerfunction (event:KeyboardEvent):void
{
trace("keyHandlerfunction: " + event.keyCode);
}
}
If you would like to make a comment, please fill out the form below.
nice tutorial..
Hey this is very good and simple example to understand Key handling in AS3. It is really helpfull.
Not a good tutorial. It fails to show how to catch specific words or keys.
I’ve spent some 200 hours developing a nice telnet & vt100 terminal emulator for flash player 9. Works pretty well on my development machine (OS X), but then I tried it on XP and Vista. At first it seemed ok, but then I noticed that there were keys that I could not write… On a swedish keyboard layout, shift+2 is supposed to give ‘”‘, but it gives ‘@’ as CharCode in flash. Shift-7 is supposed to give ‘/’, but it gives ‘&’ and there are a few other errors. So to be able to use KeyBoardEvent.charCode, one has to translate it per keyboard layout and operating system, but not even that will work since some key-combinations like those needed to write a ~ character on a swedish keyboard does not give any events at all (the next character after ~ will give an extra event, if the ~ character is supposed to be written on its own).