如何在WinUI3应用程序中保存应用程序关闭或输入后台的数据



如何在WinUi 3应用程序中拦截app_closingapp_entering_background

在UWP应用程序中,我们确实有Application_EnteredBackground事件,在该事件中,我们可以拦截应用程序关闭,我们使用GetDeferral()来保存数据。

在WinUI 3应用程序中是否存在类似的事件,我需要在应用程序关闭或进入后台时保存数据

已尝试window_VisibilityChangedwindow_Closed事件,但无法使用GetDeferral()

请帮助

提前谢谢。

Noorul

这是我的测试代码供您参考,您可以拦截关闭事件。

(关闭前执行关闭(

public sealed partial class MainWindow : Window
{
private AppWindow _appWindow;
public MainWindow()
{
this.InitializeComponent();

this.Closed += OnClosed;
_appWindow = GetAppWindowForCurrentWindow();
_appWindow.Closing += OnClosing;
}

private void OnClosed(object sender, WindowEventArgs e)
{
string btnText = myButton.Content.ToString();
}

private async void OnClosing(object sender, AppWindowClosingEventArgs e)
{
string btnText =  myButton.Content.ToString();
e.Cancel = true;     //Cancel close
//Otherwise, the program will not wait for the task to execute, and the main thread will close immediately
//await System.Threading.Tasks.Task.Delay(5000); //wait for 5 seconds (= 5000ms)
Func<bool> funcSaveData = () =>
{
//perform operations to save data here
return true;
};
var funResult = await Task.Run(funcSaveData);
this.Close();   //close
}

private AppWindow GetAppWindowForCurrentWindow()
{
IntPtr hWnd = WindowNative.GetWindowHandle(this);
WindowId myWndId = Win32Interop.GetWindowIdFromWindow(hWnd);
return AppWindow.GetFromWindowId(myWndId);
}
private void myButton_Click(object sender, RoutedEventArgs e)
{
myButton.Content = "Clicked";
}
}

最新更新