rydev rydev - 3 months ago 9
C# Question

How to execute code when Universal Windows Store App is closing?

I am developing an app for Windows 10 Store app, but I can't seem to find/learn on how to check if the user pressed the red close button (at the top right) or by pressing Alt + F4. Basically what I want is something like this:

private void app_Close(object sender, CloseEventArgs e)
{
//saves some data in the app :D
}

Answer

Add a handler to your MainWindow "Closing" event to save your data. Once "Closing" has finished, "Close" should fire normally.

theMainWindowObject.Closing += (s,a) =>
    {
        SaveTheData(); // It's precious!
    };

I have something similar to this in one of my smaller applications where in the constructor for MainWindow I put the above snippet substituting "theMainWindowObject" for "this" so that it references itself

So I have:

public MainWindow()
    {
    // Note: "this." isn't necessary here but it helps me with mental accounting
    this.Closing += (s, a) =>
        {
            Save();
        };
    }

If you're just saving one or two properties and don't have any crazy logic going on you can just drop it right in the handler:

public MainWindow()
    {
    Closing += (s, a) =>
        {
            Properties.Settings.Default.SettingsPopupX = mySettingsPopupObject.GetX();
            Properties.Settings.Default.SettingsPopupY = mySettingsPopupObject.GetY();
            Properties.Settings.Default.Save();
        };
    }

.: EDIT :.

If you have a Universal app that doesn't have a MainWindow object you'll probably want to tap into the "Suspending" event:

appObject.Suspending += (s, a) =>
        {
            SaveTheData(); // I really like my data and want it for later too
        };

or

public App()
    {
    /*
        stuff
     */
    Suspending += (s, a) =>
        {
            SaveTheData(); // I really like my data and want it for later too
        };
    }
Comments