AS3 onKeyDown, Key Down listener

Another big question i get asked is how do you detect the user actioning the keyboard? It’s slightly more complicated than AS2, where you could just attach a listener directly to the Key class singleton.

Because of this I’ve seen loads of odd ways that people have tried to implement keyboard detection in AS3, from making a textfield that sits onto of everything receiving focus, to a textfield stashed in every class.

By far the simplest way is to add a listener straight to the stage e.g.

//call onKeyboardDown on key downRoblox HackBigo Live Beans HackYUGIOH DUEL LINKS HACKPokemon Duel HackRoblox HackPixel Gun 3d HackGrowtopia HackClash Royale Hackmy cafe recipes stories hackMobile Legends HackMobile Strike Hack


If you’re trying to put this in a class that extends DisplayObject like MovieClip, then you’ll have to wait until the instance has been added to another DisplayObject that’s already attached to the stage directly or in a tree. i.e. after a addChild(myDisplayClass) has been called.

You don’t have to worry about checking keyCode’s against numbers now either. The Keyboard class is full of static variables relating to practically every key on the keyboard. i.e.

protected function onKeyboardDown(event:KeyboardEvent):void

    1. this.dispatchDialogComplete();
  1. //test key code against statics in the Keyboard class
    if(event.keyCode == Keyboard.ENTER)



Here’s a clump of code to help explain:

It’s a basic LoginDialog that you’d code generate like this

var dialog = new LoginDialog();
dialog.x = 100// arbitrary
dialog.y = 100// arbitrary
//as the stage variable inside the dialog now exists, call draw() to add key listener to stage

Example: try pressing enter after adding some values



One thought to “AS3 onKeyDown, Key Down listener”

Leave a Reply

Your email address will not be published. Required fields are marked *