Reputation: 132
Objective to achieve:
- Prompt confirm message "Are you confirm to exit?", with the options "Yes" and "Cancel"
I have been finding a way to to achieve the objective written above. I have tried the following code:
Windows.UI.Core.Preview.SystemNavigationManagerPreview.GetForCurrentView().CloseRequested += async (sender, args) =>
{
args.Handled = true;
var dialog = new MessageDialog("Are you confirm to exit?", "Exit");
System.Diagnostics.Debug.WriteLine("CLOSE");
};
the above code i writtin in MainPage.xaml.cs, but this code seem like not working for me, i don't see the "CLOSE" print out in the debug output.
Upvotes: 4
Views: 1267
Reputation: 39102
After a bit of digging I have found out that app close confirmation is actually a restricted capability that you have to declare in you application manifest. Right-click the Package.appxmanifest
file in Solution Explorer and choose View code.
In the opened XML file first add the following namespace in the root Package
element:
xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
And now find the Capabilities
section where you add the confirmAppClose
capability:
<Capabilities>
<Capability Name="internetClient" />
<rescap:Capability Name="confirmAppClose" />
</Capabilities>
Also, be aware that if you will want to display the MessageDialog
, you will have to use the deferral, so that the system waits for the await
to finish before checking the Handled
property:
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);
dialog.CancelCommandIndex = 1;
dialog.DefaultCommandIndex = 1;
if (await dialog.ShowAsync() == cancelCommand)
{
//cancel close by handling the event
e.Handled = true;
}
deferral.Complete();
The advantage of this approach compared to just terminating the app manually and setting the event as Handled
every time is that in this case the app first goes through the suspension lifetime event, which allows you to save any unsaved changes, whereas Application.Terminate()
for example would mean an immediate "hard-kill" of the app.
Upvotes: 3