How to detect exit for UWP

后端 未结 2 1557
失恋的感觉
失恋的感觉 2021-01-19 05:41

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 appli

2条回答
  •  轮回少年
    2021-01-19 06:31

    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"
    ...
     
       
       
     
    

    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.

提交回复
热议问题