AIR中通过关闭主窗口关闭所有子窗口

默认下,在AIR中点击本地窗口的关闭按钮时只会关闭当前窗口。然而在开发多窗口应用时,可能需要在关闭主应用程序窗口的同时关闭所有子窗口。我们可以在Event.CLOSING事件中取消默认的关闭操作,通过遍历手动关闭所有已打开的窗口。

看下面代码:

import flash.display.NativeWindow; 
import flash.display.NativeWindowInitOptions; 
import flash.display.NativeWindowType; 
import flash.events.Event; 
import flash.desktop.NativeApplication; 
  
stage.nativeWindow.addEventListener(Event.CLOSING, closeAllWindows); 
addNewWin("First Window"); 
addNewWin("Second Window"); 
  
function addNewWin(title:String):void { 
    var opt:NativeWindowInitOptions = new NativeWindowInitOptions(); 
    opt.type = NativeWindowType.NORMAL; 
    var win:NativeWindow = new NativeWindow(opt); 
    win.title = title; 
    win.width = 400; 
    win.height = 200; 
    win.activate(); 
} 
  
function closeAllWindows(event:Event):void { 
    event.preventDefault(); 
    //loop through all windows and close them 
    var windows:Array = NativeApplication.nativeApplication.openedWindows; 
    var count:int = windows.length; 
    for (var i:int = 0; i < count; i++) { 
        var closeWin:NativeWindow = windows[i] as NativeWindow; 
        closeWin.close(); 
    } 
}

在本实例中,主窗口的关闭操作是在Event.CLOSING事件中通过preventDefault()方法来取消的。这样,您就取消Closing事件的默认行为,主窗口不会自动关闭。然后,通过NativeApplication.nativeApplication.openedWindows属性取得此应用程序的所有已打开的本地窗口,循环调用close()方法关闭它们。

发表评论