BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Windows Programming
.NET 1.1+

Detecting the Tab Key in Windows Forms

Most keypresses in Windows Forms applications can be detected using a mixture of the KeyDown, KeyUp and KeyPress events. However, as the tab key is used to move between controls, it is not captured by these events and must be handled differently.

Overriding ProcessCmdKey

The tab key is used by Microsoft Windows to signify that the focus should move to the next control in the tab order of the current form. Pressing shift and tab together moves the focus in the reverse direction. As this is a standard system key, the KeyDown, KeyUp and KeyPress events that are available to controls do not respond to the tab key. However, it is possible to detect these key combinations by overriding the ProcessCmdKey method that is defined for all forms and custom controls.

The ProcessCmdKey method is executed every time a key is depressed in a similar manner to the KeyDown event of a control. The method has a parameter named keyData that contains information relating to the keys that have been pressed.

The downside to using ProcessCmdKey rather than a KeyDown event is that the method executes for the entire form rather than an individual control. This means that if you are simulating the event for a single control, you must also check to see if that control has the focus. Alternatively, you can create a custom control and override the ProcessCmdKey method in its class.

The method returns a Boolean value that indicates whether the key has been processed. If you return true, the key processing is completed so in the case of the tab key, the focus will not change.

The following code, added to a form, checks if the tab key is pressed with or without the shift key whilst the focus is in a textbox named 'textBox1'. If either key combination is used, a message is displayed and the focus remains within the textbox.

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    bool baseResult = base.ProcessCmdKey (ref msg, keyData);

    if (keyData == Keys.Tab && textBox1.Focused)
    {
        MessageBox.Show("Tab pressed");
        return true;
    }

    if (keyData == (Keys.Tab | Keys.Shift) && textBox1.Focused)
    {
        MessageBox.Show("Shift-Tab pressed");
        return true;
    }

    return baseResult;
25 January 2008