Control the Windows Phone 8.1 WinRT Back Button

Note: this technique is for Windows Phone 8.1 WinRT apps only. For previous versions of Windows Phone (including Windows Phone 8.1 Silverlight apps) see my previous post. This post shows how to intercept the Back button in Windows Phone 8.1 WinRT apps. You should have a good reason for doing this (see the previous post linked in the not above for details) or you may fail certification (or have an app that users find counter-intuitive).

App Templates and Navigation

WinRT apps have a great NavigationHelper class built in (except for the Blank App template). NavigationHelper does what you’d guess: it automates navigation, including the Back button behaviour. If your page uses NavigationHelper you need to modify NavigationHelper’s class a tiny bit. If you aren’t using it (e.g. you used the Blank App template and handle all navigation yourself) you can skip this step.

Modify NavigationHelper

Open NavigationHelper.cs (it will be in the Common folder) and replace the HardwareButtons_BackPressed method with the following:

private void HardwareButtons_BackPressed(object sender, Windows.Phone.UI.Input.BackPressedEventArgs e)
{
    if (this.GoBackCommand.CanExecute(null) && !e.Handled)
    {
        e.Handled = true;
        this.GoBackCommand.Execute(null);
    }
}

All we’ve done here is add ” && !e.Handled” to that if statement. This changes NavigationHelper to only navigate backwards if the Back button press has not been handled elsewhere first. This is because we want the option to override the Back button completely.

Add a Namespace

Add the following namespace to your page:

using Windows.Phone.UI.Input;

Add the Handler

Add the handler to the page’s constructor method (e.g. public MainPage()):

HardwareButtons.BackPressed += OnBackPressed;

This tells your page to execute a method called OnBackPressed when the Back button is pressed.

Add the Overriding Code

You’ve told the page to call OnBackPressed when the Back button is pressed, so now you need to create that method. What goes in here is really up to you. You can close a popup, navigate to a specific page, etc.

private async void OnBackPressed(object sender, Windows.Phone.UI.Input.BackPressedEventArgs e)
{         
    e.Handled = true;
    // add your own code here to run when Back is pressed
}

That single line “e.Handled = true” is important. The e.Handled state tells the OS if the Back button press has been dealt with (“handled”). When you set this to true the OS considers the matter dealt with; if you leave it (i.e. as false) the OS will still continue with the normal Back button behaviour after running your method (i.e. your method would run, and then the default backwards navigation would happen).

Control the Windows Phone Back Button (Windows Phone Silverlight 7 / 8 / 8.1)

Note: This method for overriding the Windows Phone Back button is for Silverlight apps only. Windows Phone 8.1 WinRT apps (including universal apps) do not support this method. I will do a separate post for Windows Phone 8.1 WinRT.

By default Windows Phone keeps pages on a ‘back stack’ and automatically navigates backwards through that stack (eventually exiting the app) when you press the hardware Back button. This is intuitive, but you may want to override the behaviour from time to time.

However, keep in mind that the expected behaviour – that pressing Back takes the user back a step – should be preserved (you’ll likely fail certification if it isn’t). Overriding the Back button is not intended to let you assign the Back button to random functions (e.g. pausing audio playback); you should override the Back button when doing so preserves the user experience in an intuitive, logical way. For example I have an app that uses popup windows to display content. If a popup window is displayed and the user presses Back, the window closes, but the page does not navigate backwards.

Overriding the Back Button

To override the Back button you need a very simple method in your page’s code behind.
Firstly, add the ComponentModel namespace to your page:

using System.ComponentModel;

Then add this method:

protected override void OnBackKeyPress(CancelEventArgs e)
{
    // put any code you like here
    MessageBox.Show("You pressed the Back button");
    e.Cancel = true;                       
}

This little method overrides the default Back button behaviour with whatever you put inside it. There is one important line of code I’ve added in the above method:

e.Cancel = true;

Setting e.Cancel to true tells the OS to cancel the default Back button behaviour (i.e. navigating to the previous page). If you leave that line out your method would run, and then the phone would also navigate backwards (which may be the behaviour you want).

Handling the Windows Phone 8 Back Button in Unity

Windows Phone apps must support the hardware back button. This button gives the user control of their phone, such as easily returning to the previous screen or exiting an application.

Since Unity is cross-platform, there is no specific command to support Windows Phone’s back button, but it’s easy to implement.

Unity treats the Back button as if it’s a keyboard’s Esc (escape) key, so we just need to detect when this ‘virtual’ Esc key is pressed. Add the following code where you detect user input (typically the Update() method):

#if (UNITY_WP8 && !UNITY_EDITOR) // only run this if the target platform is WP8 and the game is not running in the Unity editor
            if (Input.GetKey(KeyCode.Escape))
            { 
              OnBackButtonPressed(); 
            }  
#endif

The above code is calling a method called OnBackButtonPressed(), which you must now create, and add in code to take the appropriate action (e.g. to navigate to another screen or to close the application).

void OnBackButtonPressed()
{
  // add code here to handle the back button press
  Application.LoadLevel("PreviousScreen");
}

I put the escape key detection code in every scene in a script’s Update() method, and create a specific OnBackButtonPressed() method for each scene. For example, pressing Back from the Settings or About screens should take the player back to the main menu. Perhaps in your game pressing back on the game screen should pause the game, then return to the menu if is pressed a second time.

Keep the user experience and Windows Phone guidelines in mind when implementing the Back button. It must work intuitively. Don’t use the Back button as a control for your game. Use it to take the user back one level in the hierarchy of your game.

Plug time:
To see this technique in action in an actual Unity game on Windows Phone you can check out my game Clowntraptions:
http://www.grogansoft.com/Presskit/sheet.php?p=clowntraptions