Creating interactivity and visual effects 569
Capturing keypresses
You can use the global on() handler to intercept the built-in behavior of keypresses in Flash
Player, as shown in the following example:
/* When you press the Left or Right Arrow key, the movie clip to which the
handler is attached changes transparency. */
on (keyPress "<Left>") {
this._alpha -= 10;
}
on (keyPress "<Right>") {
this._alpha += 10;
}
Make sure that you select Control > Disable Keyboard Shortcuts, or certain keys with built-in
behavior won’t be overridden when you use Control > Test Movie to test the application. See
the
keyPress parameter of on handler in the ActionScript 2.0 Language Reference.
You can use the methods of the built-in Key class to detect the last key that the user pressed.
The Key class does not require a constructor function; to use its methods, you call the
methods on the class, as shown in the following example:
Key.getCode();
You can obtain either virtual key codes or American Standard Code for Information
Interchange (ASCII) values of keypresses:
■ To obtain the virtual key code of the last key pressed, use the getCode() method.
■ To obtain the ASCII value of the last key pressed, use the getAscii() method.
A virtual key code is assigned to every physical key on a keyboard. For example, the left arrow
key has the virtual key code 37. By using a virtual key code, you ensure that your SWF file’s
controls are the same on every keyboard, regardless of language or platform.
ASCII values are assigned to the first 127 characters in every character set. ASCII values
provide information about a character on the screen. For example, the letter “A” and the letter
“a” have different ASCII values.