9.15. Detecting Keystrokes

Problem

You want to detect when the user presses a key on the keyboard.

Solution

Add a listener object to the Key class.

Discussion

If you want to detect key presses with Flash, you’ve got to write a small amount of ActionScript code. In order to handle keyboard interactivity, Flash uses a specific ActionScript class called Key. The Key class detects when keys are pressed and released, and it reports which keys have been pressed. When the Key class detects that some keyboard event has occurred, it sends out a notification to any object that has been registered with it as a listener. A listener object is an ActionScript construct that you can register with the Key class once, and each time the Key class dispatches notifications, the listener object can respond appropriately. All you need to do is tell the listener object what ActionScript code it should run when it gets a notification.

Key class listener objects can receive notifications for two types of keyboard events: keys being pressed and released. In order to handle those events, define event handler methods on the listener object with the names onKeyDown( ) and onKeyUp( ).

The onKeyDown( ) method, as the name would suggest, gets called when a key is pressed. And similarly, the onKeyUp( ) method is called when a key is released.

If defining listener objects and custom event handler methods is new to you, don’t worry. It requires only a few lines of code. The following code defines a listener object as well ...

Get Flash 8 Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.