Question

I have a universal Windows Phone app (started from the Blank App template) consisting of a MainPage and three secondary pages. Navigation among these is working as expected (thanks to, in part, this MSDN page).

The problem I'm running into is that when on the MainPage, when the users presses the hardware Back button, my app is put in the background, but the card for my app remains in the task switcher. This happens regardless of whether the debugger is attached or not.

I tried this in a new project based on the Pivot App (WP) template, and I see the same issue.

I want to "close" my app when the user presses Back from the MainPage, so that it's no longer in the task switcher. Is there something I need to be doing manually?

Was it helpful?

Solution

You can exit your app with Application.Current.Exit(); in the HardwareButtons_BackPressed function below.

public MainPage()
{
    Windows.Phone.UI.Input.HardwareButtons.BackPressed += HardwareButtons_BackPressed;
}

private void HardwareButtons_BackPressed(object sender, Windows.Phone.UI.Input.BackPressedEventArgs e)
{
    /* When you don't know the namespace you can use this code instead of the lower

    string[] Namespace = Frame.CurrentSourcePageType.FullName.Split('.');
    if (!e.Handled && Frame.CurrentSourcePageType.FullName == Namespace[0] + ".MainPage")
            Application.Current.Exit();
    */
    if (!e.Handled && Frame.CurrentSourcePageType.FullName == "NAMESPACE.MainPage")
        Application.Current.Exit();
}

I hope this works

regards, Christian

OTHER TIPS

This is how I ended up implementing it, with the pointers from user2799780 and Romasz, although I'm not 100% sure that I'm not double-(un)registering the handler. It depends on whether there always is a NavigatedFrom for each NavigatedTo, I guess.

EDIT: I've been reminded (see comments) that when being suspended, an app receives the OnNavigatedFrom event, but when resuming, it won't see a OnNavigatedTo event, causing the handler to not be registered in that case. The below implementation is likely affected by this bug.

protected override async void OnNavigatedTo(NavigationEventArgs e)
{
    // When we're on this page, pressing Back should close the app
    Windows.Phone.UI.Input.HardwareButtons.BackPressed += HardwareButtons_BackPressed;
}

protected override async void OnNavigatedFrom(NavigationEventArgs e)
{
    // When we leave this page, pressing Back should no longer close the app
    Windows.Phone.UI.Input.HardwareButtons.BackPressed -= HardwareButtons_BackPressed;
}

private void HardwareButtons_BackPressed(object sender, Windows.Phone.UI.Input.BackPressedEventArgs e)
{
    if (!e.Handled)
    {
        Application.Current.Exit();
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top