Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Program doesn't stop after new Window

Tags:

c#

.net

wpf

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?

like image 991
MTR Avatar asked Apr 26 '11 14:04

MTR


2 Answers

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.

  1. 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.

  2. 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.

  3. 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.

like image 180
Cody Gray Avatar answered Oct 18 '22 09:10

Cody Gray


you can use this code to close all windows

  private void CloseAllWindows()
  {
     foreach(var window in Application.Current.Windows)
        window.Close();
  }
like image 35
Stecya Avatar answered Oct 18 '22 10:10

Stecya