Exiting a Windows Phone Application Programatically
This is just a helpful tip for those who do Windows Phone development. I had issues on trying to figure out what the best way was to exit my app from the app’s main root page. For a while I just threw an exception such as this:
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
base.OnBackKeyPress(e);
throw new Exception(“Exit Main”);
}
It irked me to do this, but it worked and passed Marketplace certification. Well, I was needing to perform some code on the App.xaml.cs level when exiting my app:
private void Application_Closing(object sender, ClosingEventArgs e)
{
// Do stuff here
}
Well, this code was never called due to the exception being thrown from my main page when the back button was pressed. So, I dug in a bit to the NavigationService class and realized I could actually remove all back entries that were on the back stack. Joy! So, this is what I came up with for the OnBackKeyPress event:
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
base.OnBackKeyPress(e);
if (NavigationService.CanGoBack)
{
while (NavigationService.RemoveBackEntry() != null)
{
NavigationService.RemoveBackEntry();
}
}}
And voila! It worked. The app exited properly and the Application_Closing event was called from App.xaml.cs which allowed me to do some background processing of my app’s data.
Hope this can help any of you.

