【问题标题】:Is shutdown of WPF application cause Window.Closing event?WPF 应用程序的关闭是否会导致 Window.Closing 事件?
【发布时间】:2018-04-23 14:22:58
【问题描述】:

在我的应用程序中,我有主窗口,用户可以从中打开另一个 WPF 窗口。 当用户关闭主窗口时,我想退出应用程序,所以我写了这段代码:

  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);
            }
        }

但第二个窗口仍然出现并运行,因为它有一个等待信号的线程。

为了防止它,我添加了结束等待Window_Closing 事件信号的线程的代码。现在,如果用户关闭第二个窗口,它可以工作(线程停止等待,然后窗口关闭),但是如果这个窗口需要从主窗口关闭,它就不起作用,窗口继续等待。

可能Application.Current.Shutdown(); 不会导致Window.Closing 事件? 如果不是,我该如何停止在第二个窗口中的等待,或者换句话说,我知道窗口将要关闭?

谢谢。

【问题讨论】:

    标签: c# wpf window shutdown


    【解决方案1】:

    调用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()?

    【讨论】:

    • 我不能使用 ShutdownMode 因为我需要在关闭应用程序之前做一些额外的事情:(
    • 在调用方法之前执行它们然后...?或者采纳我的第二个建议。
    • 我不能。正如链接中解释的那样,这不是太残酷了吗?
    • 你不能什么?您问过如何立即关闭应用程序而无需等待,不是吗?或者你的问题是什么?
    • 如果我使用 ShutdownMode,我无法在关闭应用程序之前做额外的事情。我的问题是我如何在窗口中知道它需要关闭。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-10
    相关资源
    最近更新 更多