0

I have a WPF application that needs to save its current state every time the application exits. At the moment, I am handling the System.Windows.Application.Exit event to save the state of the application. However, it seems that the event is not invoked system reboots -- only ordinary shutdowns. Is this expected behavior?

This is what my application looks like.

public class MyApp : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
        ...
        this.Exit += OnExit;
    }
    private void OnExit(object sender, ExitEventArgs e)
    {
        SaveMyApplicationState();
    }
}

What events can I use to be notified of a system reboot, so my application state can be saved?

Trympet
  • 55
  • 2
  • 6
  • 1
    Does this answer your question? [Catch windows shutdown event in a wpf application](https://stackoverflow.com/questions/7136573/catch-windows-shutdown-event-in-a-wpf-application) – Jackdaw Oct 11 '20 at 20:50
  • Not directly, since I am able to handle ordinary shutdown events via Application.Exit at the moment, but I'll check if it solves my problem. If so, I'll submit a PR to the docs clarifying the ambiguity. – Trympet Oct 12 '20 at 14:24

1 Answers1

1

To determine when system is restarting or shutting down use the SessionEnding event:

App.xaml

<Application ...
     SessionEnding="App_SessionEnding">
    ...
</Application>

App.xaml.cs

public partial class App : Application
{
    void App_SessionEnding(object sender, SessionEndingCancelEventArgs e)
    {
        if (.../*canceling*/)
        {
            e.Cancel = true;
        }
        else
        { 
            // Processing before terminating (save current state)
            // ...               
        }
    }
}

For detailed information see documentation: Application.SessionEnding Event

NOTE: Application Shutdown Changes in Windows Vista

Jackdaw
  • 7,626
  • 5
  • 15
  • 33
  • I looked at the docs you attached, however I don't understand how the SessionEnding event differs from Application.Exit. Quoting the documention for SessionEnding: "If SessionEnding is unhandled, or is handled without being cancelled, Shutdown is called and the Exit event is raised". – Trympet Oct 12 '20 at 14:21
  • @Trympet - In documentation noted the following: `If SessionEnding is unhandled, or is handled without being cancelled, Shutdown is called and the Exit event is raised.` What the documentation not says the OS may not give enough time to application to finish executing all code inside the `Exit` event. – Jackdaw Oct 12 '20 at 15:58
  • @Trympet - If the `SessionEnding` is handled the application still have all resources and the Operating System will wait until application is executing. The application can return `FALSE` to indicate that it should not be closed. – Jackdaw Oct 12 '20 at 16:07
  • Ah okay, that makes sense. Thank you! – Trympet Oct 12 '20 at 16:23