1

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.

kmatyaszek
  • 19,016
  • 9
  • 60
  • 65
Tim
  • 2,731
  • 9
  • 35
  • 72

2 Answers2

1

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

Damian Schenkelman
  • 3,505
  • 1
  • 15
  • 19
  • Thank you for the response, Damian, but I have tried the Closing event. It does not seem to fire when I close the UI. Oddly, it also does not fire when I close the entire application. – Tim Oct 02 '12 at 19:19
  • Hmm, do this help? http://stackoverflow.com/questions/8908276/why-does-unloaded-event-of-window-do-not-fire-in-wpf http://stackoverflow.com/questions/3183729/why-isnt-my-wpf-closing-event-being-fired-for-system-closes – Damian Schenkelman Oct 02 '12 at 19:51
0

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
Community
  • 1
  • 1
Tim
  • 2,731
  • 9
  • 35
  • 72