Table of Contents

Key.onKeyDown( ) Listener Event Flash 6

occurs when a key is depressed
listener.onKeyDown()

Description

The onKeyDown( ) and onKeyUp( ) events are the keyboard analogues of Mouse.onMouseDown( ) and Mouse.onMouseUp( ). Together, they provide fundamental tools for coding keyboard-based interactivity. The onKeyDown( ) event can be handled by an event listener, as specified by listener, that has been added using addListener( ). The onKeyDown( ) event occurs whenever a key on the keyboard is depressed, including modifier keys such as Shift and Ctrl. When a key is held down, onKeyDown( ) may occur repeatedly, depending on the operating system and keyboard setup. Unlike the on(keyPress) button event, onKeyDown( ) occurs when any key�not just a specified key�is pressed.

An onKeyUp( ) event handler is sometimes preferred to onKeyDown( ) when inexperienced users, such as children, tend to hold down a key, potentially generating multiple unwanted keyDown events for each keyUp event. Conversely, an onKeyDown( ) handler is generally more responsive than an onKeyUp( ) handler and therefore should be used if responsiveness is important.

To trap (i.e., detect or catch) an onKeyDown( ) event, we must first assign a callback function to the onKeyDown property of some object, such as listener, and then add listener as a listener using Key.addListener( ), as follows:

// Create a generic object
keyListener = new Object();
   
// Assign a function to the object's onKeyDown property
keyListener.onKeyDown = function () {
  trace("Some key was pressed!");
}
   
// Register the listener with the Key object
Key.addListener(keyListener);

Any number of listener objects of any class can respond to the onKeyDown( ) event.

Keyboard events are triggered only if the Flash Player has mouse focus. Users must click the Stage of a movie before the movie's keystroke handlers will become active. Consider forcing users to click a button before entering any keyboard-controlled section of a movie. This ensures that the Flash Player has keyboard focus.

You'll notice that our preceding onKeyDown( ) function does not tell us which key was pressed. If we're waiting for generic input, such as the user pressing any key to skip to the next section of a movie, we might not care which key was pressed. But often, we want to tie some action to a specific key. For example, we might want different keys to turn a spaceship in different directions.

Using onKeyDown( ) handlers is appropriate for navigational interfaces that treat each keypress as a discrete action in need of a response (e.g., the spacebar causing a slide show presentation to advance). If you don't care which key was pressed, simply execute the desired code from your onKeyDown( ) listener. To determine which key triggered the onKeyDown event, use the Key.getAscii( ) or Key.getCode( ) method inside a conditional (if statement).

For cases when you want to know the current state of the keyboard, or in applications such as games, that require instant, continuous feedback from potentially simultaneous keypresses, use the Key.isDown( ) and Key.isToggled( ) methods instead. Those methods would ordinarily be used within a handler that is called repeatedly, allowing you to check the state of the keyboard even if the system doesn't generate repeated events while keys are being held down. For example, you might check the keyboard state within a MovieClip.onEnterFrame( ) handler, or using an interval created by setInterval( ).

The following example creates an onKeyDown( ) listener that tells us the ASCII value of the last key pressed:

keyListener = new Object();
keyListener.onKeyDown = function () {
  lastKeyPressed = String.fromCharCode(Key.getAscii());
  trace("You pressed the '" + lastKeyPressed + "' key.");
}
Key.addListener(keyListener);

The following example checks whether the up arrow was the last key pressed:

keyListener = new Object();
keyListener.onKeyDown = function () {
  // Check to see if the up arrow was the last key pressed.
  // The up arrow is represented by the Key.UP property.
  if (Key.getCode() =  = Key.UP) {
    trace("The up arrow was the last key depressed");
  }
}
Key.addListener(keyListener);

As a rule of thumb, use Key.getAscii( ) when you care about the character of the key that was pressed, such as whether it was an uppercase A or lowercase a. Use Key.getCode( ) when your care which physical key was pressed, such as when using four adjacent keys for navigation, regardless of the characters they represent. See the Discussion under the Key object entry for more information.

The onKeyDown( ) event executes immediately when a key is pressed, independent of the code on a movie's timeline(s). However, visual changes to the movie made by the listener are not rendered until the next frame refresh, which is determined by the frame rate of the movie. Unfortunately, in Flash 6, updateAfterEvent( ) cannot be used to force a screen refresh from an onKeyDown( ) listener; updateAfterEvent( ) has an effect only when invoked either from a movie clip mouse or key event, or a setInterval( ) callback.

Handling special keys

To disable the Standalone Player's contextual menu commands (Open, Close, Fullscreen, etc.), add the following line of code to the beginning of your movie:

fscommand("trapallkeys", "true");

This command also prevents the Escape key from exiting fullscreen mode in a Standalone Player. To capture Escape in a Standalone Player, use:

keyListener.onKeyDown = function () {
  if (Key.getCode() =  = Key.ESCAPE) {
    // Respond to Escape keypress
  }
}

Note that the Escape key cannot be trapped in every browser. Furthermore, there is no way to disable the Alt key or the Windows Alt-Tab or Ctrl-Alt-Delete key sequences.

The following code captures Tab keypresses:

keyListener.onKeyDown = function () {
  if (Key.getCode() =  = Key.TAB) {
    trace("Tab was the last key depressed");
  }
}

In some browsers, Flash Player 5 detects the Tab key only within an on(keyPress) button event. The following code successfully detects the Tab key in all browsers using Flash Player 5:

// CODE ON BUTTON ON MAIN TIMELINE
on (keyPress "<Tab>") {
  // Set a dummy variable here
  foo = 0;
}
   
// CODE ON MOVIE CLIP ON MAIN TIMELINE
// Notice that this is a keyUp event. The keyDown event doesn't work with
// Flash 5 running in Internet Explorer.
onClipEvent (keyUp) {
  if (Key.getCode() =  = Key.TAB) {
    // Now place the cursor in myTextField on _level0
    Selection.setFocus("_level0.myTextField");
  }
}

In Flash Player 6, the Tab key can safely be detected with a Key listener. We typically trap the Tab key in order to move the insertion point to a particular text field in a form. However, as of Flash 6, custom Tab key behavior can be controlled precisely via the tabIndex and tabEnabled properties of the TextField, MovieClip, and Button classes, without the need for any Key listeners. For a Flash 5-compatible Tab order example, see:

http://moock.org/asdg/codedepot/interface-widgets/taborder.fla

To capture a key combination, such as Ctrl-G, use:

keyListener.onKeyDown = function () {
  if (Key.isDown(Key.CONTROL) && Key.isDown(71)) {
    // Respond to Ctrl-G. Keycode 71 is the keycode for the G key.
  }
}

To capture the Enter (or Return) key, use:

keyListener.onKeyDown = function () {
  if (Key.getCode() =  = Key.ENTER) {
    // Respond to Enter keypress (e.g., submit a form)
  }
}

Usage

To emulate onKeyDown( ) in Flash 5, use a movie clip onClipEvent(keyDown) clip event attached to the clip at authoring time. For example:

onClipEvent (keyDown) {
  trace("Some key was pressed");
}

See Also

Key.addListener( ), Key.getAscii( ), Key.getCode( ), Key.isToggled( ), Key.onKeyUp( ), MovieClip.onKeyDown( )


Table of Contents