WPF UI关闭时的通知

时间:2012-10-02 19:08:06

标签: c# wpf event-handling

我正在从托盘应用打开一个WPF窗口。我使用以下代码打开窗口:

        if (gui == null)
        {
            gui = new App();
            gui.MainWindow = new mainWindow();
            gui.InitializeComponent();
            IsUIOpen = true;
        }
        else if (!IsUIOpen)
        {
            gui.InitializeComponent();
            gui.MainWindow.Show();
            gui.MainWindow = new mainWindow();
            IsUIOpen = true;
        }

我需要从App级别运行UI,因为它使用资源字典。问题是,我需要在用户关闭窗口时运行代码,但没有一个事件处理程序似乎在通知我。

我尝试了以下内容:

gui.Exit += new System.Windows.ExitEventHandler(settings_FormClosed);
gui.MainWindow.Closed += new EventHandler(settings_FormClosed);

我还尝试了gui.Deactivatedgui.SessionEndinggui.MainWindow.Closinggui.MainWindow.Deactivated以及其他一些人。

当用户关闭窗口时,将从Shell.xaml调用此代码:

    private void Cancel_Click(object sender, RoutedEventArgs e)
    {
        presenter.Close();
        this.Close();
    }

我意识到App是静态的,所以它永远不会关闭,但是这些事件处理程序中的一个应该把我联系到一个结束事件。

如果它有用,流程如下:TrayApp.cs - > App.xaml - > Shell.xaml

任何建议将不胜感激。提前谢谢。

2 个答案:

答案 0 :(得分:1)

您应该尝试Closing事件。 This article提供有关WPF何时实际关闭(而不仅仅是窗口)的有用信息。

答案 1 :(得分:0)

Josh能够提供正确的解决方案。你可以看到他的回答here

基本上,我需要将WPF作为一个单独的进程启动,然后使用MyProcess.WaitForEnd()调用。我把它添加到一个线程,所以它不会阻止托盘。代码如下:

Process myProcess = new Process();
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.FileName = "C:\\mysettingsapp\\mysettingsapp.exe"; // replace with path to your settings app
myProcess.StartInfo.CreateNoWindow = false;
myProcess.Start();
// the process is started, now wait for it to finish
myProcess.WaitForExit();  // use WaitForExit(int) to establish a timeout