1
votes

I have a simple WPF application with a MainWindow. Set up an unloaded event in the code behind. Set the MainWindow as the startup uri. Unloaded is not triggered when the window is closed. Create a second window - NotMainWindow with a single button click.

In the button click event, call MainWindow. Close MainWindow and unloaded is triggered. Why the difference in behaviour? What I am trying to get at is, how do I get some kind of unloaded event every single time?

<Window x:Class="WpfApplication2.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525" Unloaded="Main_Unloaded">
<Grid>

</Grid>
</Window>

    private void Main_Unloaded(object sender, RoutedEventArgs e)
    {

    }

<Window x:Class="WpfApplication2.NotMainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="NotMainWindow" Height="300" Width="300">
<Grid>
    <Button Content="Show Main" Height="25" Margin="10" Width="70" Click="Button_Click" />
</Grid>
</Window>


private void Button_Click(object sender, RoutedEventArgs e)
    {
        MainWindow win = new MainWindow();
        win.Show();
    }

<Application x:Class="WpfApplication2.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         StartupUri="NotMainWindow.xaml">
<Application.Resources>

</Application.Resources>
</Application>
1
It is not called when it is closed. That is the issue. Of course it wouldn't be called on load! :PHarsha
@Blachshma - Corrected the question to remove the confusion.Harsha
So you're saying that you create the MainWindow and then immediately close it and the unloaded is not called?Blachshma
Yeah. By immediately, I mean, pretty much anytime after the window is rendered on the screen.Harsha

1 Answers

3
votes

Based on your comments I understand the scenario you're talking about. This is a known issue that unloaded is not called when shutting down the application (e.g. last window is closed).

If you just want to know when the window is closed use the Closing event:

public MainWindow()
{
    this.Closing += new CancelEventHandler(MainWindow_Closing);
    InitializeComponent();
}


void MainWindow_Closing(object sender, CancelEventArgs e)
{
   // Closing logic here.
}

If you want to know when the last window is closed, e.g. your application is shutting down, you should use ShutdownStarted

public MainWindow()
{
    this.Dispatcher.ShutdownStarted += Dispatcher_ShutdownStarted;
    InitializeComponent();
}

private void Dispatcher_ShutdownStarted( object sender, EventArgs e )
{
   //do what you want to do on app shutdown
}