Search code examples
windowsapache-flexairflex-spark

Spark WindowedApplication, monitor keyUp event


I have a WindowedApplication, I need to monitor a keyUp so that I can close the application on the escape key pressed. However, my code is not working:

<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009" 
                       xmlns:s="library://ns.adobe.com/flex/spark" 
                       xmlns:mx="library://ns.adobe.com/flex/mx"
                       keyUp="windowedapplication1_keyUpHandler(event)">

<fx:Script>
        <![CDATA[   

            protected function windowedapplication1_keyUpHandler(event:KeyboardEvent):void
            {
                //Monitor key press {ESC}
                if(event.keyCode == 27){
                    exit();
                }
                else{
                    trace("key = " + event.keyCode);
                }
            }   

        ]]>
</fx:Script>

It seems that this event is not firing at all, I've even tried to override the keyUpHandler and trace out some info, but nothing.


Solution

  • I found this similar question on the Adobe forums, it helped solve the problem.

    I solved by listening for applicationComplete and then in the handler attaching the keyUp listener to the stage.

    <s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009" 
                           xmlns:s="library://ns.adobe.com/flex/spark" 
                           xmlns:mx="library://ns.adobe.com/flex/mx"
                           applicationComplete="init()">
    
    <fx:Script>
            <![CDATA[   
    
                protected function init():void
                {
                    stage.addEventListener(KeyboardEvent.KEY_UP, windowedapplication1_keyUpHandler);
                }
    
                protected function windowedapplication1_keyUpHandler(event:KeyboardEvent):void
                {
                    //Monitor key press {ESC}
                    if(event.keyCode == 27){
                        exit();
                    }
                    else{
                        trace("key = " + event.keyCode);
                    }
                }       
    
            ]]>
    </fx:Script>