Code to Disable the Hardware Back Button in Windows Phone 7


You may have come across a requirement where you need to disable the hardware back button in Windows Phone 7. 

BckBtnWinPhn1.gif

If you want to disable the hardware back button on Page1 then you need to override OnBackKeyPress method on Page1.

BckBtnWinPhn2.gif

To disable you need to set the CancelEventArgs value to cancel as given below,

BckBtnWinPhn3.gif

If you want, you can display a message to user when users try to navigate from back button. For your reference, the code to disable the back button is given below.

using System.Windows;
using Microsoft.Phone.Controls;
 
namespace PhoneApp1
{
    public partial class SecondPage : PhoneApplicationPage
    {
        public SecondPage()
        {
            InitializeComponent();
        }
        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            //base.OnBackKeyPress(e);

            MessageBox.Show("You can not use Hardware back button");
             e.Cancel = true
        }

  }
}


When run this code and try to navigate using back button, you will get a message and hardware back button will not work. You can have any other business requirement code in overridden OnBackKeyPress method as well. I hope this post is useful. Thanks for reading.
 

Up Next
    Ebook Download
    View all
    Learn
    View all