开发者

Program doesn't stop after new Window

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 i开发者_如何学运维s 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.

  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.


you can use this code to close all windows

  private void CloseAllWindows()
  {
     foreach(var window in Application.Current.Windows)
        window.Close();
  }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜