Avg. Rating 4.1

Problem

You want to trigger some sort of action whenever a key is pressed, regardless of which part of your application has focus.

Solution

Add a KeyboardEvent.KEY_DOWN or KeyboardEvent.KEY_UP event listener to the Stage object.

Detailed explanation

Handling key presses at a global level is a very useful technique, enabling powerful functionality such as support for keyboard shortcuts within your application. However, the way you accomplish global keyboard event handling in Flex is not as obvious as you might presume it would be.

Your first instinct might be to use the Application class's <code>keyDown</code> event handler or to register a <code>KeyboardEvent.KEY_DOWN</code> event listener with the Application when it first starts up. However, the Application only receives keyboard events while one of its child controls has focus. If nothing is focused then no keyboard events will be received by the Application object.

The solution is to register a <code>KeyboardEvent.KEY_UP</code> or <code>KeyboardEvent.KEY_DOWN</code> listener with the Stage, not the Application. In Flex 2 the Stage is not globally accessible (as it was in previous versions of Flex) but instead is accessible via the <code>stage</code> property of any DisplayObject, including the Application object, so you must access it via this property.

One tricky hurdle to get over is deciding when exactly you should register the listener. It turns out that if you try to register it too early - for example when the Application's <code>initialize</code> or <code>creationComplete</code> event handlers are triggered - the <code>stage</code> property won't yet contain a reference to the Stage. Instead, you should trigger your event registration code from the Application's <code>applicationComplete</code> event handler as shown below.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical"
	backgroundColor="#FFFFFF"
	applicationComplete="registerGlobalKeyHandler()">
	
	<mx:Script>
		<![CDATA[
			public function registerGlobalKeyHandler() :void
			{
				stage.addEventListener(KeyboardEvent.KEY_DOWN, handleKeyDown);
			}
			
			public function handleKeyDown(event:KeyboardEvent) :void
			{
				display.text = "Key was pressed: " + event.keyCode;
			}
		]]>
	</mx:Script>
	
	<mx:Label id="display"
		text="Click anywhere in the application and then press some keys." />
	
</mx:Application>

Author: Kristopher Schultz - Resource Interactive (www.resource.com)

Report abuse

Related recipes