Detect Application closing in UWP

Corrado Cavalli
Corrado Cavalli
Published in
2 min readMay 11, 2018

Nearly every application when user closes it using the “X” button on upper right corner prompts something like this

image

Asking user if he wants to save actual work or cancel closing operation.
Doing this in a UWP application is far from trivial, sounds strange uh?

Smile

Despite some options are available (like CoreWindow esposes a Closed event but it never fires) the only available solution sounded to be this one which is unfortunately complex and unreliable.
From Creators update (version 1703) a new class SystemNavigationManagerPreview has been added and this class exposes a CloseRequested event (yeah!)
Ok, let’s see how it works, let’s fire up a brand new UWP app inside Visual Studio and let’s add this code inside MainPage.Xaml codebehind.

Let’s put a breakpoint inside OnCloseRequested method, run the app and try closing the window clicking the upper right “X” button.
The breakpoint doesn’t it right? so What’s wrong with that? nothing indeed, we just miss an important detail: In order to work, you need to add a restricted capability inside package.appmanifest, the one we need is AppClose Confirmation that MSDN describes as: confirmAppClose restricted capability allows apps to close themselves, their own windows, and delay the closing of their app.

Ok, let’s manually edit the manifest file adding following lines:

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

then add rescap to IgnorableNamespacesAttribute: IgnorableNamespaces=”uap mp rescap”
Then inside Capabilities tag:
<Capabilities>
<Capability Name=”internetClient” />
<rescap:Capability Name=”confirmAppClose”/>
</Capabilities>


Very important: confirmAppClose capability must be listed before any optional DeviceCapability otherwise it won’t work.
Let’s now try again and… yes! it works!

Smile

You can now do whatever you want inside the OnCloseRequest handler, like showing a dialog and if user denies closing setting SystemNavigationCloseRequestedPreviewEventArgs.Handled=true to prevent app from closing.

Please take care of the note inside capabilities declaration page on MSDN:

Some of these restricted capabilities are almost never approved for apps submitted to the Store, except in very specific and limited circumstances. These capabilities are called out in the table below. We recommend not declaring these capabilities in your app if you plan to distribute it through the Store.

I see no reason why Microsoft should prevent this but take note and don’t forget to mention its use inside portal Submission options page

--

--

Corrado Cavalli
Corrado Cavalli

Senior Sofware Engineer at Microsoft, former Xamarin/Microsoft MVP mad about technology. MTB & Ski mountaineering addicted.