Keyboard Demo
Click on the flash screen below to start the demo showing keyboard inputs. Press any key and you will see the key code that you pressed.
The code for this demo is presented at the bottom of the page. I created a class called Key which I can reuse for other programs that need to detect keyboard input.
KeyDemo.as (Source Code)
package {
import flash.display.Sprite;
import flash.events.Event;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
public class KeyDemo extends Sprite {
var t : TextField = new TextField;
public function KeyDemo() {
key.initKey(stage);
t.autoSize = TextFieldAutoSize.LEFT;
addChild(t);
stage.addEventListener(Event.ENTER_FRAME, showKeys);
}t.autoSize = TextFieldAutoSize.LEFT;
addChild(t);
stage.addEventListener(Event.ENTER_FRAME, showKeys);
public function showKeys(e : Event) {
var s : String = "";
var i : int;
for (i = 0; i < key.MAXKEY; i++) {
t.text = s;
}var i : int;
for (i = 0; i < key.MAXKEY; i++) {
if (key.k[i]) { s = s + "Key[" + i.toString() + "] pressed "; }
}t.text = s;
}
}
Key.as (Source Code)
package {
import flash.events.KeyboardEvent;
public class key {
static const MAXKEY = 128;
// keycode declarations
static const RIGHT = 39;
static const LEFT = 37;
static const UP = 38;
static const DOWN = 40;
static const PLUS = 107;
static const EQUAL = 187;
static const MINUS = 109;
static const UNDERSCORE = 189;
static const SPACE = 32;
static const ENTER = 13;
public static var k : Array = new Array(MAXKEY); // stores all key states as boolean
// adds keyboard handler to provided object
public static function initKey(o : Object) {
var i : int;
for (i = 0; i < MAXKEY; i++) {
o.addEventListener(KeyboardEvent.KEY_UP, keyUpListener);
}for (i = 0; i < MAXKEY; i++) {
k[i] = false; }
o.addEventListener(KeyboardEvent.KEY_DOWN, keyDownListener);o.addEventListener(KeyboardEvent.KEY_UP, keyUpListener);
public static function keyDownListener(e : KeyboardEvent) {
k[e.keyCode] = true;
}public static function keyUpListener(e : KeyboardEvent) {
k[e.keyCode] = false;
}}
}