M3579
M3579

Reputation: 910

Code to run when app closes

I've found plenty of examples of writing code that executes when a WPF or Windows Forms app terminates, but not for a UWP app. Is there any special C# method you can override, or an event handler you can use to contain cleanup code?

Here is the WPF code I tried but did not work in my UWP app:

App.xaml.cs (without the boilerplate usings and namespace declaration)

public partial class App : Application
{
        void App_SessionEnding(object sender, SessionEndingCancelEventArgs e)
        {
            MessageBox.Show("Sorry, you cannot log off while this app is running");
            e.Cancel = true;
        }
}

App.xaml

<Application x:Class="SafeShutdownWPF.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:SafeShutdownWPF"
             StartupUri="MainWindow.xaml"
             SessionEnding="App_SessionEnding">
    <Application.Resources>

    </Application.Resources>
</Application>

I tried to use Process.Exited, but VS2015 could not recognize Process inside of System.Diagnostics.

Upvotes: 6

Views: 1609

Answers (1)

Kevin Gosse
Kevin Gosse

Reputation: 39037

For UWP apps, you need to use the Suspending event on the Application object. If you used the default project template then you should already have a OnSuspending method defined, you just have to fill it. Otherwise, subscribe to the event in the constructor:

public App()
{
    this.InitializeComponent();
    this.Suspending += OnSuspending;
}

And the method should look like (using a deferral to allow asynchronous programming):

private void OnSuspending(object sender, SuspendingEventArgs e)
{
    var deferral = e.SuspendingOperation.GetDeferral();
    //TODO: Save application state and stop any background activity
    deferral.Complete();
}

Upvotes: 4

Related Questions