AS3 Basics: Detect flash window focus with Actionscript 3.0

Hello again,

I’ve been playing about and discovered a neat simple code snippet to detect if the flash file has focus. By focus i mean if the user has clicked on the embedded flash on a web page.

EXAMPLE

if say you had a game, and the user were to click away accidently? you’d want to use that event to pause the game.

I’m not going to bore you with an explanation of the code as we have covered everything previously.
All we’re using here thats different from before are different events.

function main():void
{
    stage.addEventListener(Event.DEACTIVATE, windowNotActive);
    stage.addEventListener(Event.ACTIVATE, windowActive);
}
main();

function windowNotActive(e:Event):void
{
    trace("NOT ACTIVE");
}

function windowActive(e:Event):void
{
    trace("ACTIVE");
}

Demonstration

5 Comments

  1. Sorry but I have one big problem : I can’t do the same in AS2….I cant port my game to AS3 because I dont have the time, but I’d really like to warn the user when the flash loses focus because my game uses keybord inputs and players dont understand why they cannot play anymore after ALT-TAB ALT-TAB
    I’d greatly appreciate any help on this problem. I’ve done it in AS3 , even tried to add an invisible AS3 flahs next to my game but it doesn’t have the focus when the game has it, so it cannot detect ALT-TAB
    :[

  2. Hmm tricky, i don’t know of any way to achieve it in AS2. Did you try embedding you’re AS2 game into an AS3 swf?

  3. Hi again Jerem, so i got thinking about you’re problem and as long as you don’t have any hold ups about publishing in AS3 you can analyze this example to achieve what you want LINK :)

  4. Great, thanks!

    I for one didn’t need this for pausing the game, I just wanted to know the syntax for seeing when the flash went out of focus so that I can use multiple keypresses in AS3 without glitches if you hold a key while deactivating the flash and then releasing the key after.

  5. I’m trying to load and external swf that has a button in it. For some reason, the button (and the entire swf) is completely inactive when I run the movie. I suspect that the problem has to do with me loading the swf, and it not getting focus, but I’m not sure how to fix this.

Leave a Reply