应用程序关闭时编码为 运行

Code to run when app closes

我发现了很多编写代码的示例,这些代码在 WPF 或 Windows Forms 应用程序终止时执行,但不是针对 UWP 应用程序。是否有任何可以重写的特殊 C# 方法,或者是否有可用于包含清理代码的事件处理程序?

这是我试过但在我的 UWP 应用程序中不起作用的 WPF 代码:

App.xaml.cs(没有样板使用和命名空间声明)

public partial class App : Application
{
        void App_SessionEnding(object sender, SessionEndingCancelEventArgs e)
        {
            MessageBox.Show("Sorry, you cannot log off while this app is running");
            e.Cancel = true;
        }
}

App.xaml

<Application x:Class="SafeShutdownWPF.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:SafeShutdownWPF"
             StartupUri="MainWindow.xaml"
             SessionEnding="App_SessionEnding">
    <Application.Resources>

    </Application.Resources>
</Application>

我尝试使用 Process.Exited,但 VS2015 无法识别 System.Diagnostics 中的进程。

对于 UWP 应用程序,您需要在 Application 对象上使用 Suspending 事件。如果您使用默认的项目模板,那么您应该已经定义了一个 OnSuspending 方法,您只需填写它。否则,在构造函数中订阅事件:

public App()
{
    this.InitializeComponent();
    this.Suspending += OnSuspending;
}

方法应该如下所示(使用延迟以允许异步编程):

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