Application Exit without exception

Due to the missing App.Exit() method for Windows Phone Apps it is not so easy to exit an app from every page of an app. What can you do if you want to exit your app by a click or the BackKeyPress event?

For example: You can exit your app if the backkey is pressed by raising an exception which mostly will fail the certification to the marketplace or you can use the following code to exit your WP7 app without an exception. I want to exit Cryp2pass if the user does press the back key and the loginPopup is opened. It is only tested with mango and will be implemented in the next version of Cryp2pass.

I use the follwing code to exit my app:

private void PhoneApplicationPage_BackKeyPress(object sender, CancelEventArgs e)
{
    if (App.loginPopup.IsOpen)
    {
        while (NavigationService.BackStack.Any())
            NavigationService.RemoveBackEntry();
    }
}

or

protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
    if (App.loginPopup.IsOpen)
    {
        while (NavigationService.BackStack.Any())
            NavigationService.RemoveBackEntry();
    }
}

The code

while (NavigationService.BackStack.Any())
    NavigationService.RemoveBackEntry();

does completely remove the app from the NavigationService and does exit your app normally and does call Application_Closing like the user did press the back key on the first page of your app.

Don’t call NavigationService.GoBack() after removing all BackEntries because it will raise an exception. The two lines of code are enough to exit your app.

I hope this will help you for your app and i would be happy about all comments.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s