Sunday, February 22, 2009

How to set focus on a Flex app (and how to reset it after losing it)

If you are running a Flex app and click on another app, you'll lose focus from the Flex app. In most programs in order to regain focus you just reclick the app and off you go. However Flash does not regain focus automatically unless the user clicks on some element that has an onClick event listener set up for it. This can be a problem especially if you have an app that is supposed to run using keyboard controls only (like a slideshow).

In order to regain focus, make sure that your main component on the stage -- like the canvas that holds your app -- has a click listener set up like this:

click="enableKeyListener(event)"

and then you can have a function that is called like this:

public function enableKeyListener(evt:Event):void{
application.addEventListener(KeyboardEvent.KEY_DOWN,keyUpListener);
world.setFocus();
}

You'll note that the enableKeyListener function is called by the application on creationComplete and explicity calls setFocus() on an element that exists on the stage. And it needs to do this again if you want to regain focus. AFAIK there is no setFocus() method in the stage object so you need to choose an element that is on the stage instead.

No comments: