Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to intercept the TAB key press to prevent standard focus change in C#

Normally when pressing the TAB key you change the focus to the next control in the given tab order. I would like to prevent that and have the TAB key do something else. In my case I'd like to change focus from a combobox to a completely different control. I can't do this by setting the tab order. I need to do this programatically. Any idea how? It seems like the KeyDown and KeyPress events can't handle TAB key correctly. Thanks.

like image 327
John Avatar asked Sep 20 '10 08:09

John


2 Answers

Override ProcessDialogKey or ProcessTabKey on your Form and do the logic you want depending on which control is focused.

like image 70
liggett78 Avatar answered Oct 31 '22 12:10

liggett78


Based on JRS's suggestion of using the PreviewKeyDown event, this sends the key press through to the control:

private void textBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
    if (e.KeyCode == Keys.Tab)
        e.IsInputKey = true;
}

Then you can handle the control's KeyDown event if you want to customise the behaviour:

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Tab)
    {
        MessageBox.Show("The tab key was pressed while holding these modifier keys: "
                + e.Modifiers.ToString());
    }
}

TextBoxBase alternative

If the control is derived from TextBoxBase (i.e. TextBox or RichTextBox), with the Multiline property set to true, then you can simply set the AcceptsTab property to true.

TextBoxBase.AcceptsTab Property

Gets or sets a value indicating whether pressing the TAB key in a multiline text box control types a TAB character in the control instead of moving the focus to the next control in the tab order.

like image 30
Zantier Avatar answered Oct 31 '22 13:10

Zantier