简体   繁体   English

WPF应用程序的关闭是否引起Window.Closing事件?

[英]Is shutdown of WPF application cause Window.Closing event?

In my app I have the main window, the user can open another WPF windows from it. 在我的应用程序中,我有主窗口,用户可以从中打开另一个WPF窗口。 When the user closes the main window I want to exit from the application, so I Wrote this code: 当用户关闭主窗口时,我想从应用程序退出,因此我编写了以下代码:

  private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            try
            {
                if (onClosingAppFlag == true)
                    return;

                string s = "       Exit the application ?" + Environment.NewLine +
                            "(Exit process duration is about 5 seconds)" + Environment.NewLine +
                            "       Are you sure? ";
                MessageBoxResult dres = MessageBox.Show(this, s, "Exit from RTS",
                    MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (dres == MessageBoxResult.No)
                {
                    e.Cancel = true;
                    return;
                }

                onClosingAppFlag = true;
                App.Current.Shutdown();
                OnClosingApp();

            }
            catch (Exception ex)
            {
                string line = "Error, Exeption occuredd at MainWindow.Window_Closing() : " + Environment.NewLine + ex.Message;
                AppWinServices.Singleton.LogFileWrite(line);
            }
        }

But the second window still appears and running because it has a thread that waits for signals. 但是第二个窗口仍然显示并正在运行,因为它有一个等待信号的线程。

To prevent it I added code that ends the thread that waiting for signals on Window_Closing event. 为了防止这种情况,我添加了代码,该代码结束了在Window_Closing事件上等待信号的线程。 Now if the user closes the second window it works (The thread stop to wait and then the window becomes closed), but if this window needs to be closed from the main window it doesn't work and the window continue to wait. 现在,如果用户关闭第二个窗口,则它可以工作(线程停止以等待,然后窗口关闭),但是,如果需要从主窗口中关闭该窗口,则该窗口不起作用,并且该窗口继续等待。

It can be that Application.Current.Shutdown(); 可以是那个Application.Current.Shutdown(); doesn't cause to Window.Closing event? 不会导致Window.Closing事件? and if not how can I stop the waiting in the second window or in other words where I know the window is going to be closed? 如果没有,如何在第二个窗口中停止等待,换句话说,我知道该窗口将要关闭?

Thanks. 谢谢。

Call Environment.Exit(0) or set the ShutdownMode property to OnMainWindowClose in your App.xaml.cs : 调用Environment.Exit(0)或在App.xaml.cs中将ShutdownMode属性设置为OnMainWindowClose

protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);
    ShutdownMode = ShutdownMode.OnMainWindowClose;
}

what's difference between Environment.Exit() and Application.Shutdown()? Environment.Exit()和Application.Shutdown()有什么区别?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM