air 2.0 on application quit, call preventDefault

2019-04-01 13:07发布

问题:

Trying to prevent the application from shutting down when clicked the X button, it still closing but the AIR process is running in the task manager. What wrong with the code?

Application Complete:

NativeApplication.nativeApplication.addEventListener(Event.EXITING, onExiting);

Closing code:

private function onExiting(e:Event):void
{
e.preventDefault();
}

回答1:

Try Event.CLOSING. That's what I use to cancel closing.

Event.EXITING happens after the window is removed and should be used only for cleanup, and not to prevent the application from closing.

From the docs:

On Windows, the only time you will get the exiting event is after closing the last window (when autoExit=true).


Sample "unclosable" application:

<?xml version="1.0" encoding="utf-8"?>
<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"
                       initialize="init()">
    <fx:Script>
        <![CDATA[
            import mx.controls.Alert;

            private function init():void{
                this.addEventListener(Event.CLOSING, function(e:Event):void{
                    e.preventDefault();
                    Alert.show('Unclosable!');
                });
            }
        ]]>
    </fx:Script>
</s:WindowedApplication>

Good luck,
Alin



回答2:

Alert message processing happens in different thread than application thread so application do not wait for alert message box. The trick is to have a global variable with initialized value of false. On event handler for close, cancel close event if value is not changed to true. This allows alert message to show up. If user pressed Yes then set the variable to true and again fire exit function.

        private var boolExit:Boolean=false;

        private function alertClickHandler(event:CloseEvent):void{
            if(event.detail==Alert.YES){
                boolExit=true;
                NativeApplication.nativeApplication.exit();
            }

        }


        private function AppExit(e:Event):void{
            if(!boolExit)
                e.preventDefault();

            Alert.show("Do you want to exit application?",
                "Exit Confirmation",
                Alert.YES|Alert.NO,null,
                alertClickHandler
                );
        }

        public function init():void
        {
           . . . 
           this.addEventListener(Event.CLOSING,AppExit);
           . . .
        }


标签: flex air