How to handle hardware back button in Windows Phone

August 28, 2013 by Anuraj

.Net Windows Phone

If you want to display an exit confirmation from your Windows Phone app, if user press the hardware back button, here is the code snippet. (It is not a recommended practice, as per Windows Phone market place certification requirements, if user pressing the back button from the application’s first page, application should exit)

protected override void OnBackKeyPress(CancelEventArgs e)
{
    if (MessageBox.Show("Are you sure want to exit?", "Confirm", 
        MessageBoxButton.OKCancel) != MessageBoxResult.OK)
    {
        e.Cancel = true;
    }

    base.OnBackKeyPress(e);
}

It will display a message box like this, if user press the back button. WP7 Exit confirmation

Clicking on OK will exit the application.

Happy Coding.

Copyright © 2024 Anuraj. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Powered by Jekyll. Hosted with ❤ by GitHub