当系统关闭 UWP 应用程序时,如何获取终止或终止事件?

Vik*_*ana 5 .net c# events windows-10 uwp

在设置中更改联系人访问会终止UWP应用程序。

系统关闭应用程序时如何获取terminatingterminated事件?

Par*_*ami 0

App.xaml.cs文件中App类的构造函数中的订阅UnhandledException和事件Suspending

    public App()
    {
        this.InitializeComponent();
        this.Suspending += OnSuspending;
        this.UnhandledException += App_UnhandledException;
    }
Run Code Online (Sandbox Code Playgroud)

每当应用程序发生异常时,就会触发此事件

private async void App_UnhandledException(object sender, Windows.UI.Xaml.UnhandledExceptionEventArgs e)
    {
        // do your job

        e.Handled = true;
    }
Run Code Online (Sandbox Code Playgroud)

您还可以设置Handled异常属性true,以防止应用程序崩溃并以不良方式关闭。

每当您的应用程序执行被挂起时,就会触发此事件

    /// <summary>
    /// Invoked when application execution is being suspended.  Application state is saved
    /// without knowing whether the application will be terminated or resumed with the contents
    /// of memory still intact.
    /// </summary>
    /// <param name="sender">The source of the suspend request.</param>
    /// <param name="e">Details about the suspend request.</param>

    private async void OnSuspending(object sender, SuspendingEventArgs e)
    {
        var deferral = e.SuspendingOperation.GetDeferral();
        //TODO: Save application state and stop any background activity

        deferral.Complete();
    }
Run Code Online (Sandbox Code Playgroud)