Key.getCode( ) Method | Flash 5 |
returns the keycode of the last key pressed |
An integer representing the keycode of the last key pressed.
The getCode( ) method returns the keycode of the last key that was pressed; the keycode is an arbitrary number representing the physical location of a key on the keyboard. On non-Windows operating systems, the native keycode system is translated automatically by Flash to the Windows equivalent, so getCode( ) provides a cross-platform means of detecting specific physical keys. The getCode( ) method can also be used to differentiate between two keys with the same ASCII value. For example, it can differentiate between the 8 key on the main keyboard and the 8 key on the numeric keypad, whereas getAscii( ) cannot. However, getCode( ) cannot differentiate between upper- and lowercase letters (for example, A and a use the same keycode because they are produced using the same key). Nor does it detect modifier keys such as the Ctrl or Shift key.
Many common keycode values are available as properties of the Key object, as shown in Table 18-8 under the Description for the Key object. To determine the keycode of a particular key, see Appendix B, or construct a keycode tester as follows:
Create a new Flash document.
On frame 1, add the following code:
var keyTester = new Object(); keyTester.onKeyDown = function () { trace(Key.getCode()); } Key.addListener(keyTester);
Choose Control Test Movie.
Choose Control Disable Keyboard Shortcuts.
Click the movie's Stage.
Press a key. The key code for that key will appear in the Output window.
Unlike isDown( ), getCode( ) is useful for creating interfaces in which an individual key press has a single, direct result. Both getAscii( ) and getCode( ) are typically used with an onKeyDown( ) event listener, so that they are called once and only once per keypress.
For example, the user may be allowed to skip a movie's intro by pressing the spacebar. When the spacebar is depressed, we send the playhead to the main interface of the movie (on the main timeline) as follows:
keyListener = new Object(); keyListener.onKeyDown = function () { if (Key.getCode() = = Key.SPACE) { _root.gotoAndStop("mainInterface"); } } Key.addListener(keyListener);
Button keyPress, Key.getAscii( ), Key.isDown( ); Appendix B