Dela via


How to: Override the Smartphone Back Key

Note

Note that back key functionality is critical for navigating between Smartphone applications. In most cases, it is contrary to Smartphone user interface guidelines to alter the default navigation behavior of the back key. Use discretion in determining when to override this functionality.

You can customize the back key in Smartphone applications, such as for a game. It operates according depending on the context of the key press, as described in the following table.

Back Key Operation

Context

Cancels modal dialog boxes.

Always.

Cancels shortcut menus.

Always.

Performs a backspace operation.

When the focus is on an editable control, such as a text box, or on an editable custom control.

Navigates to the next window in the z-order.

Note that when the focus is on a form or custom control, the back key raises a KeyPress event that you can handle to provide your own functionality, as demonstrated in the example.

If you do not handle the event, the focus navigates to the next window in the z-order.

When the focus is on a form, non-editable control (such as a radio button), or non-editable custom control.

The back key operates the same way regardless of whether there is a menu bar. A menu bar exists if the form contains a MainMenu component.

Example

The following code example shows how to implement custom back key functionality. When the back key is pressed on a form or custom control, it raises the KeyPress event with the KeyChar value equal to the ESC key (27). In the event handling code, determine whether the ESC key value was raised. If it was, cancel the default back key operation by setting the Handled property to true. If the event arguments are not handled, the back key navigates to the next window in the z-order.

Visual C# users need to define an event hander for the KeyPress event in the form's constructor.

// Connect an event handler to the KeyPress event 
this.KeyPress += new KeyPressEventHandler(OnKeyPress);
Private Sub keypressed(ByVal o As [Object], _
    ByVal e As KeyPressEventArgs) Handles MyBase.KeyPress
    ' Determine if ESC key value is raised. 
    If e.KeyChar = ChrW(Keys.Escape) Then 
        ' Handle the event to provide your own functionality.
        e.Handled = True 

        ' Add  your event handling code here.
        MessageBox.Show("Custom back key functionality.")
    End If 
End Sub
private void OnKeyPress(object sender, KeyPressEventArgs ke)
{
    // Determine if ESC key value is pressed. 
    if (ke.KeyChar == (Char)Keys.Escape)
    {
        // Handle the event to provide functionality.
        ke.Handled = true;

        // Add your event handling code here.
        MessageBox.Show("Back key was pressed.");
    }
}

Compiling the Code

This example requires references to the following namespaces:

See Also

Tasks

How to: Override Smartphone Soft Keys

Other Resources

Smartphone Development and the .NET Compact Framework