Search code examples
c#wpfvisual-studio-2013window

WPF app doesn't shut down because of invisible main window instance


Some mysterious things are happening to my WPF app. I changed main window and after closing it app doesn't shut down. Here's my App.xaml:

    <Application
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:local="clr-namespace:LogAnalysis" x:Class="LogAnalysis.App"
         StartupUri="ChartWindow.xaml" ShutdownMode="OnMainWindowClose">
        <Application.MainWindow>
            <local:ChartWindow/>
        </Application.MainWindow>
    </Application>

I tried to figure out why process is still alive after closing and wrote this:

    foreach (var window in Application.Current.Windows)
    {
        MessageBox.Show((window as Window).Title);
    }

Two message boxes with the same message were shown. So, it seem like there are two instances of main window are running in the one instance of app.

I can't use solution with this:

    protected override void OnClosed(EventArgs e)
    {
        base.OnClosed(e);
        Application.Current.Shutdown();
    }

because Window.Closing event is triggered twice because of the second instance of the window (and it corrupts user settings).


Solution

  • Oh, finally got it. In the App.xaml file there is no need to determine Main Window property explicity. So, this code is not only redundant, it also calls window constructor:

        <Application.MainWindow>
            <local:ChartWindow/>
        </Application.MainWindow>
    

    It will be enough to change only StartupUri property.

    Hope it will help someone.