Capturing keyboard input



Display objects that inherit their interaction model from the InteractiveObject class can respond to keyboard events by using event listeners. For example, you can place an event listener on the Stage to listen for and respond to keyboard input. In the following code, an event listener captures a key press, and the key name and key code properties are displayed:

function reportKeyDown(event:KeyboardEvent):void 
{ 
    trace("Key Pressed: " + String.fromCharCode(event.charCode) +         " (character code: " + event.charCode + ")"); 
} 
stage.addEventListener(KeyboardEvent.KEY_DOWN, reportKeyDown);

Some keys, such as the Ctrl key, generate events even though they have no glyph representation.

In the previous code example, the keyboard event listener captured keyboard input for the entire Stage. You can also write an event listener for a specific display object on the Stage; this event listener is triggered when the object has the focus.

In the following example, keystrokes are reflected in the Output panel only when the user types inside the TextField instance. Holding the Shift key down temporarily changes the border color of the TextField to red.

This code assumes there is a TextField instance named tf on the Stage.

tf.border = true; 
tf.type = "input"; 
tf.addEventListener(KeyboardEvent.KEY_DOWN,reportKeyDown); 
tf.addEventListener(KeyboardEvent.KEY_UP,reportKeyUp); 
 
function reportKeyDown(event:KeyboardEvent):void 
{ 
    trace("Key Pressed: " + String.fromCharCode(event.charCode) +         " (key code: " + event.keyCode + " character code: "         + event.charCode + ")"); 
    if (event.keyCode == Keyboard.SHIFT) tf.borderColor = 0xFF0000; 
} 
 
function reportKeyUp(event:KeyboardEvent):void 
{