Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect exit for UWP

Tags:

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.

like image 345
qakmak Avatar asked Dec 15 '22 05:12

qakmak


2 Answers

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.

like image 54
Romasz Avatar answered Jan 21 '23 19:01

Romasz


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 (i.e. save or prompt). Also, you can set Handled to true in order to stop the window from closing (i.e. 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.

like image 32
Soumya Mahunt Avatar answered Jan 21 '23 19:01

Soumya Mahunt