WinUI3应用如何拦截关闭/进入后台事件并保存数据?
WinUI3 拦截应用关闭/进入后台事件并保存数据的方案
在WinUI3中,有对应UWP Application_EnteredBackground 和关闭场景的替代方案,以下是具体实现方式:
1. 处理应用进入后台/激活前台(对应EnteredBackground场景)
WinUI3基于Windows App SDK,可通过AppLifecycleHelper监听应用生命周期状态变化,实现进入后台的逻辑处理:
using Microsoft.Windows.AppLifecycle; using Microsoft.UI.Xaml; public partial class App : Application { protected override void OnLaunched(Microsoft.UI.Xaml.LaunchActivatedEventArgs args) { // 监听应用生命周期状态变更 AppLifecycleHelper.Instance.LifecycleStateChanged += OnLifecycleStateChanged; } private void OnLifecycleStateChanged(object sender, LifecycleStateChangedEventArgs e) { if (e.NewState == AppLifecycleState.Background) { // 应用进入后台,执行数据保存操作 // 异步操作需注意系统后台执行时长限制 _ = SaveAppDataAsync(); } } private async Task SaveAppDataAsync() { // 模拟异步保存数据逻辑 await Task.Delay(1000); } }
2. 处理应用关闭事件(对应关闭场景)
使用窗口的Closing事件(而非Closed事件),该事件支持GetDeferral()方法实现异步延迟关闭,和UWP的延迟机制一致:
// 在应用启动时注册窗口Closing事件 protected override void OnLaunched(Microsoft.UI.Xaml.LaunchActivatedEventArgs args) { MainWindow mainWindow = new MainWindow(); mainWindow.Closing += MainWindow_Closing; mainWindow.Activate(); } private async void MainWindow_Closing(object sender, WindowClosingEventArgs e) { // 获取延迟对象,阻止窗口立即关闭 var deferral = e.GetDeferral(); try { // 执行异步保存数据操作 await SaveAppDataAsync(); } finally { // 完成操作后释放延迟,允许窗口关闭 deferral.Complete(); } }
关键说明
Window.Closing是拦截应用关闭的核心事件,Closed事件是关闭完成后触发,因此无法实现延迟操作,需替换为Closing事件。- 进入后台场景,WinUI3无直接的
EnteredBackground事件,但通过监听AppLifecycleState.Background状态可实现相同效果,异步操作需控制执行时长,避免被系统终止。
内容的提问来源于stack exchange,提问作者Noorul
相关产品推荐
相关产品推荐

