Table of Contents

Button keyPress Event Handler Flash 4

occurs when the specified key is pressed
on (keyPress key) {  
  statements
}

Description

The keyPress event is triggered by the pressing of a specified key. It uses the Flash 5-style on(eventName) syntax and is not available in the more modern callback-function form. In Flash 6, Key.onKeyUp( ) and Key.onKeyDown( ) are the preferred keyboard-handling tools, because they do not require an on-stage object and support the detection of multiple simultaneous key presses.

To trap key events, we specify the key that triggers the event, using the syntax listed at the beginning of this entry, where key is a string representing the key associated with the event. The string can be either the character corresponding to the key (such as "s" or "S", because it is case-insensitive) or a keyword representing the key in the format "<Keyword>". Only one key can be specified with each handler. To capture multiple keys using keyPress, we must create multiple keyPress event handlers. For example:

// Detects the "a" key
on (keyPress "a") {
  trace("The 'a' key was pressed");
}
   
// Detects the Enter key
on (keyPress "<Enter>") {
  trace("The Enter key was pressed");
}
   
// Detects the down arrow key
on (keyPress "<Down>") {
  trace("The down arrow key was pressed");
}

The legal values of Keyword are as follows (note that the function keys, F1 through F12, are not supported by keyPress but are detectable using the Key object):

<Backspace>
<Delete>
<Down>
<End>
<Enter>
<Home>
<Insert>
<Left>
<PgDn>
<PgUp>
<Right>
<Space>
<Tab>
<Up>

In Flash 4, keyPress was the only means of interacting with the keyboard.

Usage

Unlike all other keyboard event-handling tools in ActionScript, the keyPress Button event intercepts the default keyboard behavior in the Player. For example, if a button traps the left arrow key via keyPress, the left arrow will not move the I-beam cursor in a text field.

on ( keyPress "<Left>" ) {
  // We're just blocking the <Left> key, but we must provide some code here
  // or this function will get optimized out.
  1 + 1;
} 

See Also

Key.onKeyDown( ), Key.onKeyUp( )


Table of Contents