UWP on desktop closed by top X button - no event

A restricted capability confirmAppClose was added in Windows 10 version 1703 (build 10.0.15063) in order to provide apps the ability to intercept window closing.

Manifest namespace:

xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"

Manifest:

<Capabilities> 
  <Capability Name="internetClient" /> 
  <rescap:Capability Name="confirmAppClose"/> 
</Capabilities> 

It needs extra approval when submitting to the store. But then will fire the CloseRequested event on a SystemNavigationManagerPreview instance.

Code:

    public MainPage()
    {
        this.InitializeComponent();
        SystemNavigationManagerPreview.GetForCurrentView().CloseRequested += this.OnCloseRequest;
    }

    private void OnCloseRequest(object sender, SystemNavigationCloseRequestedPreviewEventArgs e)
    {
        if (!saved) { e.Handled = true; SomePromptFunction(); }
    }

You can get a deferral to do a bit of work here (save or prompt), or you can set Handled to true in order to stop the window from closing (user cancelled prompt).


This code helps you -

In App.xaml.cs

...
using Windows.ApplicationModel;
...

public App()
{
    InitializeComponent();            
    this.Suspending += OnSuspending;
}
...
private void OnSuspending(object sender, SuspendingEventArgs e)
{
    var deferral = e.SuspendingOperation.GetDeferral();
    //Add your logic here, if any
    deferral.Complete();
}

Thanks!!!


From official page about app lifecycle:

There's no special event to indicate that the user closed the app.

Closed-by-user behavior: If your app needs to do something different when it is closed by the user than when it is closed by Windows, you can use the activation event handler to determine whether the app was terminated by the user or by Windows.

So according to this there is no (clear) way to know if the user closed the app before the app is closed but only after it's restarted. Too bad.