Notification when WPF UI closes

落爺英雄遲暮 提交于 2019-12-04 05:19:59

问题


I am opening a WPF window from a tray app. I use the following code to open the window:

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

I need to run the UI from the App level because it uses a Resource Dictionary. The problem is, I need to run code when the window is closed by the user, but none of the event handlers seem to be notifying me.

I have tried the following:

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

I have also tried gui.Deactivated, gui.SessionEnding, gui.MainWindow.Closing, gui.MainWindow.Deactivated, and probably some others.

When the user closes the window, this code is called from Shell.xaml:

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

I realize App is static, so it will never close, but one of these event handlers should hook me up to a closing event.

In case it is useful, flow is as follows: TrayApp.cs -> App.xaml -> Shell.xaml

Any suggestions would be appreciated. Thanks in advance.


回答1:


You should try out the Closing event. This article provides useful information about when a WPF is actually closing (not just the window).




回答2:


Josh was able to give the correct solution. You can see his answer here.

Basically, I needed to start the WPF as a separate process, and then use the MyProcess.WaitForEnd() call. I added this to a thread so it wouldn't block the Tray. The code is as follows:

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


来源:https://stackoverflow.com/questions/12696649/notification-when-wpf-ui-closes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!