How to detect Back button presses from a Direct3D app for Windows Phone 8
Applies to: Windows Phone 8 and Windows Phone Silverlight 8.1 only
This topic shows you how to detect when the user presses the Back button from a Windows Phone Direct3D app.
Windows Phone managed apps are made up of one or more pages. As the user navigates around the app, the operating system maintains a stack of pages the user has visited. When the user presses the Back button, the app automatically navigates backward through the pages until it reaches the first page. If the user presses the Back button when there are no more pages on the back stack, the app is terminated. This is the only way to quit a Windows Phone app.
Windows Phone Direct3D apps don’t use pages, or maintain a navigation history. For games, there is a single loop, and your app determines what content, such as a start screen, a pause menu, or the game itself, to render. By default, when the user presses the Back button in a Direct3D app, the app is terminated as if it were the initial page of a managed app. If you want to allow the user to press the Back button to pause the game and view a pause menu, you need to subscribe to the BackPressed() event. In the handler for this event, you can set the Handled() of the associate event args to true, which causes the system to ignore the key press, and your app isn’t terminated. If your app is on its start screen and it doesn’t make sense to navigate backward, leave the Handled() property set to false—the default value—and the app will be terminated as the user expects.
Detecting Back button presses from a Direct3D app
Create a new Direct3D project. This example assumes you name the project “NativeFundamentals”.
In the NativeFundamentals.h header file, declare the handler for the BackPressed() event. Also, declare a member variable to indicate whether the app should navigate when the Back button is pressed.
In NativeFundamentals.cpp, add a reference to the Windows.Phone.UI.Input namespace.
In NativeFundamentals.cpp, in the OnActivated method that is included with the project template, hook up the handler for the BackPressed() event.
In the OnBackButtonPressed event handler, check to see if your app should perform a navigation. If so, set Handled() to true and do your navigation. If not, leave Handled() set to false and the app will exit.