WP7–ChildWindow & Handling the Hardware Back Button

Posted by Blake on 11/3/2011
)

I have a class that I’m using that creates a child window in the form of a dialog. The class came from Silverlight and I first learned about it from a post that Shawn Wildermuth made (http://wildermuth.com/2010/08/17/Using_ChildWindow_in_Windows_Phone_7_Projects).

In Windows Phone 7, the hardware back button closes a dialog box when it appears. With the ChildWindow however, the underlying form still has the focus, so if you hit the hardware back it exists out of the program which isn’t desirable (and breaks usability standards since the dialog doesn’t behave like other dialogs). To handle this, you want to override “OnBackKeyPress” on your main form and if the dialog is visible, close it and then cancel the hardware back (otherwise, let it function as normal). This will recreate the behavior of a normal dialog. In the below snippet, I have a reference to my ChildWindow as a property. If it’s null, the hardware back key press functions like normal. If it’s not null, the ChildWindow is closed and the back button cancels so it doesn’t exit the program. As a note, I’m currently running this code against WP7 Mango.

''' <summary>
''' Handle the hardware back key press.  If a ChildWindow is shown, close it and then cancel so focus is returned to
''' the main form.  In every other case the hardware back should function has normal.  This will essentially recreate
''' the same functionality that exists for a standard dialog. 
''' </summary>
''' <param name="e"></param>
''' <remarks></remarks>
Protected Overrides Sub OnBackKeyPress(e As System.ComponentModel.CancelEventArgs)
    If Me.RestartGameWindow IsNot Nothing Then
        Me.RestartGameWindow.Close()
    End If

    e.Cancel = True
    MyBase.OnBackKeyPress(e)
End Sub