Using the Keyboard in AS3

by kirupa   |   26 October 2011

  Have questions? Discuss this Flash / AS3 tutorial with others on the forums.

Just as often as you rely on the mouse for input, you use your keyboard as well. Writing an application that listens for key presses is a little different than writing one for mouse presses. Part of the reason is that almost all mice these days have only two buttons with a mouse wheel. It is easy to bucket everything you can do with a mouse into a few click and scroll events.

With keyboards, because you have many keys to deal with, you have a few extra hoops to jump through before you can detect which key was pressed. Don't worry, this tutorial will show you how you can use the keyboard and its keys in AS3.

The following example shows a small Flash application that reacts to keyboard input:

Click anywhere inside the above application with your mouse to give it focus. Once you have given the application focus, go ahead and press any of the keys on your keyboard. Notice that as you press a key, the key's numerical code is displayed. You also have the ability to use modifier keys such as Shift and Ctrl, so be sure to try that out as well if you haven't already.

Quick Overview of Events
Detecting which keys are pressed in Flash involves events and event handlers! First, you assign an event listener that listens for any events caused by the keyboard. When the event listener hears a key press, it calls a function known as an event handler that takes it from there.

With keyboard input, you have one additional step if you want to treat each key press differently. You need to explicitly specify what to do when a particular key has been pressed, but you have no way of doing that by simply equating the key press to a letter or number found on your keyboard. This may sound bizarre and/or confusing, so I will elaborate on this later. I just want to leave this out there so that you are adequately suspicious if things seem too easy!

Looking at the Code
In the previous section, I described in words how you would detect which key was pressed. Let's move on and actually begin to look at the AS3 code translation of the English text. What you see below is the code that I wrote for the example you played with a few hundred pixels earlier:

function setup() {
stage.addEventListener(KeyboardEvent.KEY_DOWN, displayKey);
}
setup();
 
function displayKey(keyEvent:KeyboardEvent) {
var modifier:String="";
var keyPressed:String="";
 
if (keyEvent.ctrlKey) {
modifier="Ctrl + ";
} else if (keyEvent.altKey) {
modifier="Alt + ";
} else if (keyEvent.shiftKey) {
modifier="Shift + ";
}
 
keyPressed=keyEvent.keyCode.toString();
 
myTextField.text=modifier+keyPressed;
}

Let's go through the code...starting at the very top:

function setup() {
stage.addEventListener(KeyboardEvent.KEY_DOWN, displayKey);
}
setup();

The first function that gets called when your app runs is setup, and it contains the code that specifies our event listener. The event listener takes two arguments. It first needs to know what event to listen for (KeyboardEvent.KEY_DOWN), and after that, it needs to know what event handler to call when it hears the event.

Before we look at the arguments to event listener, let's figure out when our event listener will be active. That is commonly controlled by specifying which element must have focus in order for the event listener to fire, and in turn, your event listener is attached to that element. Because my example is very simple, I assign the event listener to my entire stage itself:

stage.addEventListener(KeyboardEvent.KEY_DOWN, displayKey);

This means, if my stage has focus, then any keys I press will be recognized by my event listener. You have a lot of flexibility on which element you can assign your event listener to, though. For your application, you can be a bit more specific and assign your event listener to a text field, button, etc.

Ok, now that we got that out of the way, let's go back to the arguments we pass in to our event listener. Because we are dealing with keyboard input, listening for the KeyboardEvent along with the KEY_DOWN constant is fitting. The second argument specifies the event handler that will get called when our event listener detects a KEY_DOWN event. This event handler (a fancy name for a function that handles events) is called displayKey. Let's look at that next.


function displayKey(keyEvent:KeyboardEvent) {
var modifier:String="";
var keyPressed:String="";
 
if (keyEvent.ctrlKey) {
modifier="Ctrl + ";
} else if (keyEvent.altKey) {
modifier="Alt + ";
} else if (keyEvent.shiftKey) {
modifier="Shift + ";
}}
 
keyPressed=keyEvent.keyCode.toString();
 
myTextField.text=modifier+keyPressed;
}

Whenever a key is pressed, our event listener routes this event to the displayKey event handler, and it takes one argument of type KeyboardEvent represented by the keyEvent variable. The reason for this argument is that our event listener is listening for a KeyboardEvent.KEY_DOWN event. Because of what the listener is listening for, the event that gets passed in to this event handler is not generic. Instead, it is a bit more specific, for the event's type is actually KeyboardEvent. This is good, for KeyboardEvent provides some handy methods and properties that make working with keys much easier as you will see shortly.


var modifier:String="";
var keyPressed:String="";

These two lines are pretty straightforward. I declare two variables called modifier and keyPressed that are of type string. I initialize them to be empty.


if (keyEvent.ctrlKey) {
modifier="Ctrl + ";
} else if (keyEvent.altKey) {
modifier="Alt + ";
} else if (keyEvent.shiftKey) {
modifier="Shift + ";
}

Finally, we get to something exciting! In this block of code, I basically check if my Ctrl, Alt, or Shift keys have been pressed. If they have been pressed, I set our modifier variable to indicate which of the modifier keys was made active.

I easily check which modifier key was pressed by seeing if a value was returned by calling the keyEvent's ctrlKey, altKey, and shiftKey properties. For the record, getting Alt to work is tricky because hitting Alt will almost always shift focus away from your Flash application and towards your browser's menu bar. I've listed it here just for completeness. I have not seen it working haha.


keyPressed=keyEvent.keyCode.toString();

This line is probably the most important one you will need to know. It is this line that takes all of your keyboard inputs and returns a numerical value of the key that was pressed. This is returned by the keyEvent's keyCode property. Because I am setting the value returned by keyEvent.keyCode to our keyPressed string variable, I call the toString() method on it to convert the number into a string.


myTextField.text=modifier+keyPressed;

This line is pretty straightforward. I am appending the values of our modifier and keyPressed strings into one chunk to be displayed by a text field aptly named myTextField.


Reacting to Certain Key Presses
In many real world applications, you will rarely have a need to display the number of the key that you press. More than likely, you will want your application to do something when a key such as Enter, any of the Arrow keys, etc. are pressed. The code I have provided doesn't help you really with this case...or does it?!

It turns out that the code I provided does help, and the solution is a little bit roundabout. What you have to do is know the numerical representation of the key press you are interested in detecting. Once you know that number, you can equate your KeyboardEvent's keyCode property to this number instead.

For example, if I want my application to do something when the up, down, left, and right arrows are pressed, the following code shows you one way of doing this:

function reactToArrowKeys(keyEvent:KeyboardEvent) {
 
if (keyEvent.keyCode == 38) {
trace("Up Arrow pressed.");
} else if (keyEvent.keyCode == 40) {
trace("Down Arrow pressed.");
} else if (keyEvent.keyCode == 37) {
trace("Left Arrow pressed.");
} else if (keyEvent.keyCode == 39) {
trace("Right Arrow pressed.");
}
}

How do I know what the keycode for the various arrows are? I simply test it out an application similar to what I showed for my example. I noted down what number was returned when I hit each of the arrow keys, and once I had those numbers, it was just a matter of checking if any keycodes that were returned by my KeyboardEvent event handler matched the numbers that map to the arrow keys.


To see my version of the above application with all of the code and design, you can download the Flash CS4 source files from below.

Download Final Source

Getting Help

If you have questions, need some assistance on this topic, or just want to chat - post in the comments below or drop by our friendly forums (where you have a lot more formatting options) and post your question. There are a lot of knowledgeable and witty people who would be happy to help you out

Share

Did you enjoy reading this and found it useful? If so, please share it with your friends:

If you didn't like it, I always like to hear how I can do better next time. Please feel free to contact me directly via e-mail, facebook, or twitter.

Brought to you by...

Kirupa Chinnathambi
I like to talk a lot - A WHOLE LOT. When I'm not talking, I've been known to write the occasional English word. You can learn more about me by going here.

Add Your Comment (or post on the Forums)

blog comments powered by Disqus

Awesome and high-performance web hosting!