How to Save data on application close or entered background in WinUI3 app

Viewed 62

How to intercept app_closing or app_entering_background in WinUi 3 app.

In UWP apps we do have Application_EnteredBackground event , in which we can intercept app close, we use GetDeferral() to save data .

Is there any same kind of event in WinUI 3 apps, I need to save data on app close, or entering background.

Tried window_VisibilityChanged and window_Closed events, but not able to use GetDeferral().

Kindly help

Thanks in advance .

Noorul

1 Answers

Here is my test code for your reference, you can intercept the closing event.

(closing is executed before closed)

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";
    }
}
Related