I was developing an app in UWP where I needed to do some cleanup when the window was closed, and the only way that I had found until now was to used the Application event OnSuspending, but it was somewhat cumbersome. I wanted something that was fired when the user clicked the “X” button in the window.

With WinForms or WPF you have some events that fire when the window was closed, but in UWP, there weren’t such events.  Then I found the Restricted Capabilities. These are not normal capabilities, that you can edit using the Package.AppXManifest editor in Visual Studio. To edit them, you must open the XML file directly and add them. One other problem with them is that you will need special approval when submitting the app to the store, but that’s better than the alternative.

To use this capability, you must edit the package.appxmanifest manually. Right click on it in the Solution Explorer and select View Code. Then, in the xml, add the Restricted Capabilities namespace to the Package tag:

<Package ... 
         IgnorableNamespaces="uap mp uap6 rescap">

Then, add the confirmAppClose capability to the Capabilities node:

  <Capability Name="internetClient" />
  <uap6:Capability Name="graphicsCapture" />
  <rescap:Capability Name="confirmAppClose"/>

With that, you can use the SystemNavigationManagerPreview.GetForCurrentView().CloseRequested
event to check when the window is being closed, like this:

public MainPage()
    SystemNavigationManagerPreview.GetForCurrentView().CloseRequested+= (s, e) =>
        // Code run when the window is closing

Nice, no?