Maybe a stupid question for C#, WPF, .NET 4.0:
If I do a new on a window derived class and don't call ShowDialog on this window, my program doesn't shut down anymore on close.
Example:
Window d = new Window();
//d.ShowDialog();
Why is this so?
I don't want to show the window, I just want to use this object for some purpose. So what do I have to do in order to allow my program to shut down afterwards?
It's very likely that you've configured your application to close only when all of its windows have been closed, and by creating a new window that never gets closed, your application never gets shut down.
This setting is governed by the Application.ShutdownMode
property, which specifies the condition that causes the Shutdown
method to be called. Essentially, you have three options.
The first, as you've encountered, will not close your application unless and until all windows that it has created have been closed. It's irrelevant whether they've been closed by the user or programmatically by calling their Close
method.
This option is specified by setting the Application.ShutdownMode
property to OnLastWindowClose
.
The second method takes advantage of the fact that almost all applications have a "main" window (which is the first one you display when your application is launched), and has the runtime automatically close your entire application (and all child windows) when this main window is closed. Again, it is irrelevant whether the window is closed by the user or you close it through code.
This option is specified by setting the Application.ShutdownMode
property to OnMainWindowClose
.
The third option essentially indicates that you're going to manage things manually. It will not close the application until you call the Shutdown
method yourself through code.
This option is specified by setting the Application.ShutdownMode
property to OnExplicitShutdown
.
My recommendation, in this case, is that you set the second option, and have your app automatically close whenever the user closes the main window. That will prevent any stray child windows that may still be shown from preventing your app from closing. This eliminates the need to write the code shown in Stecya's answer, and lets the runtime handle all of this for you automatically.
you can use this code to close all windows
private void CloseAllWindows()
{
foreach(var window in Application.Current.Windows)
window.Close();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With