title: Code to run when app closes
body: <p>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?</p>
  
  <p>Here is the WPF code I tried but did not work in my UWP app:</p>
  
  <p><code>App.xaml.cs</code> (without the boilerplate usings and namespace declaration)</p>
  
  <pre><code>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;
          }
  }
  </code></pre>
  
  <p>App.xaml</p>
  
  <pre><code>&lt;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"&gt;
      &lt;Application.Resources&gt;
  
      &lt;/Application.Resources&gt;
  &lt;/Application&gt;
  </code></pre>
  
  <p>I tried to use <code>Process.Exited</code>, but VS2015 could not recognize Process inside of <code>System.Diagnostics</code>.</p>