Search code examples
uwpexit

How to do job while the application is exiting in UWP?


I have to do some cleanup job while my application is exiting.

enter image description here

My windows version.

enter image description here Capabilities in package.appxmanifest

enter image description here But the event Exiting and Closed never triggered. I do not know the problem. please help me!


Solution

  • In UWP, there is a special event for window closing: SystemNavigationManagerPreview.CloseRequested

    If you want to use this event, you need to add a special capability:

    package.appxmanifest

    <Package xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10" 
             xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest" 
             xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10" 
     
    xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
             IgnorableNamespaces="uap mp rescap">
    
    <Capabilities>
    ...
      <rescap:Capability Name="confirmAppClose"/>
    ...
    </Capabilities>
    
    </Package>
    

    After this, you can register for the event callback:

    public MainPage()
    {
        this.InitializeComponent();
    
        Windows.UI.Core.Preview.SystemNavigationManagerPreview.GetForCurrentView().CloseRequested +=
            async (sender, args) =>
            {
                args.Handled = true;
    
                // Do something
    
                App.Current.Exit();
            };
    }
    

    When your app window closing, this event will be triggered and you can perform some save operations. (Prior to this, you must set args.Handled to true to prevent the app window closing).