Basically, what we want here is to be able to catch the close event of our UWP app. We could go further and ask the users if they want to save their changes before the Exit.

In the App.xaml.cs:

protected override async void OnActivated(IActivatedEventArgs args) { Initialize(); if (null == Window.Current.Content) { Window.Current.Content = new MainPage(args); SystemNavigationManagerPreview.GetForCurrentView().CloseRequested += App_CloseRequested; Window.Current.Activate(); return; } }
Code language: C# (cs)

Here, it is important to put the CloseRequested event before the Activate of the View.

Then, add the code for the popup with the Exit confirmation:

private async void App_CloseRequested(object sender, SystemNavigationCloseRequestedPreviewEventArgs e) { var deferral = e.GetDeferral(); var dialog = new MessageDialog("Are you sure you want to exit?", "Exit"); var confirmCommand = new UICommand("Yes"); var cancelCommand = new UICommand("No"); dialog.Commands.Add(confirmCommand); dialog.Commands.Add(cancelCommand); if (await dialog.ShowAsync() == cancelCommand) { //cancel close by handling the event e.Handled = true; } deferral.Complete(); }
Code language: C# (cs)

If the user click on “No”, then we have e.Handled = true, which allows to keep the app open and cancel the Exit.

Then, open the code of the Package.appxmanifest and add this:

<Package xmlns="" xmlns:mp="" xmlns:uap="" xmlns:rescap="" IgnorableNamespaces="uap mp rescap"> <Capabilities> <Capability Name="internetClient" /> <rescap:Capability Name="confirmAppClose" /> </Capabilities>
Code language: HTML, XML (xml)

Happy coding! 🙂