简体   繁体   中英

How to detect exit for UWP

Is there any way to detect current UWP going to exit ? (close by user or kill the process)

I want to send some request to the server about the application will disconnect, also want to save some data before it exit.

There is no way to detect such case or to prevent user from terminating your app. If you want to save the state or do something before exit, use Suspending event :

The Suspending event is the only indication your app will receive prior to termination (if it happens). Because of this, you should store enough session state (such as the current article being read or the current movie playback position) to recreate the exact same experience during activation. The guidance for content creation apps is to save a user's work early and often but also commit one final save during Suspending. Saving data prior to suspension is useful because the Suspending event handler has only 5 seconds to complete its operation.

Just remember about limited time.

In fact there are two other events that will be fired (in mobile case, when user holds back button and goes to task switcher): Window.VisibilityChanged and Windows.Activated , but they are also fired when user change the app, show prompt and so on - and there is no way to distinguish those situations.

To intercept close in MainPage of the app a restricted capability confirmAppClose was added in Windows 10 version 1703 (build 10.0.15063).

Add following code to your manifest:

xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
...
<Capabilities> 
  <Capability Name="internetClient" /> 
  <rescap:Capability Name="confirmAppClose"/> 
</Capabilities> 

Then you can intercept CloseRequested event in SystemNavigationManagerPreview . You can get a deferral if your method requires some time to complete (ie save or prompt). Also, you can set Handled to true in order to stop the window from closing (ie user cancelled prompt).

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

private void OnMainPageCloseRequest(object sender, SystemNavigationCloseRequestedPreviewEventArgs e)
{
    var deferral = e.GetDeferral();

    if (!saved) 
    {
        e.Handled = true; 
        SomePromptFunction(); 
    }

    deferral.Complete();
}

You can use Window.Current.Closed or ApplicationView.GetForCurrentView().Consolidated or CoreWindow.GetForCurrentThread().Closed or CoreApplication.Exiting for all other additional windows.

Unfortunately there is no way to intercept close by killing app's process.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM