Reputation: 10054
When I want to use multiple windows in my code, I normally do it like this:
Window w = new MainWindow();
w.Show();
this.Close();
but today, I discovered I could do this:
Window w = new MainWindow();
this.Close();
w.Show();
And I was a bit surprised, so I'm wondering what exactly does this.Close
do? Yet from the documentation, it says the application will stop running (shut down) if the last window was just closed, so how come?
However, this does not work in WinForms, only WPF.
Upvotes: 0
Views: 176
Reputation: 10797
Basically, you are merely changing the order of: 1. Showing the new Window 2. Closing the current Window Since the actual rendering happens anyway after you exit from your code - there should be no difference. Regardless of the order of #1 and #2, you are never out of windows (although hidden, the second window exists), so the application will not shutdown.
Consider the following code below. Although the Show happens 3 seconds after the close of the first window, the application will not exist. Once the user click on the 'Rotate' button, the first window will disappear for 3 seconds, and a new window will appear.
XAML:
<Button Click="Button_Click" Content="Rotate" Width="80" Height="50"/>
Code-behind:
private void Button_Click( object sender, RoutedEventArgs e ) {
MainWindow w = new MainWindow( );
this.Close( );
DispatcherTimer timer = new DispatcherTimer( );
timer.Interval = new TimeSpan( 0, 0, 3 );
timer.Tick += ( o, a ) => {
( (DispatcherTimer)o ).Stop( );
w.Show( );
};
timer.Start( );
}
Upvotes: 0
Reputation: 4833
Closing a window causes any windows that it owns to be closed. Furthermore, closing a Window may cause an application to stop running depending on how the Application.ShutdownMode
property is set.
The default value for it is OnLastWindowClose
which means the application will close only after closing the last created window. At the point this.Close()
in your example you already have 2 windows (is't no matter whether a window opened or hidden).
You can see it in WPF sources, Window
s constructor adds newly created window to Application.Windows
collection. And Window.Close()
method executes the following code:
if (((App.Windows.Count == 0)
&& (App.ShutdownMode == ShutdownMode.OnLastWindowClose))
|| ((App.MainWindow == this)
&& (App.ShutdownMode == ShutdownMode.OnMainWindowClose)))
{
App.CriticalShutdown(0);
}
Upvotes: 1