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.
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.ShutdownModeproperty is set.The default value for it is
OnLastWindowClosewhich means the application will close only after closing the last created window. At the pointthis.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,
Windows constructor adds newly created window toApplication.Windowscollection. AndWindow.Close()method executes the following code: