How to make Enter on a TextBox act as TAB button


Question

I've several textboxes. I would like to make the Enter button act as Tab. So that when I will be in one textbox, pressing Enter will move me to the next one. Could you please tell me how to implement this approach without adding any code inside textbox class (no override and so on if possible)?

1
20
2/9/2015 12:03:25 PM

Accepted Answer

Here is the code that I usually use. It must be on KeyDown event.

if (e.KeyData == Keys.Enter)
{
    e.SuppressKeyPress = true;
    SelectNextControl(ActiveControl, true, true, true, true);
}

UPDATE

Other way is sending "TAB" key! And overriding the method make it so easier :)

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{            
    if (keyData == (Keys.Enter))
    {
        SendKeys.Send("{TAB}");
    }

    return base.ProcessCmdKey(ref msg, keyData);
}
21
4/26/2016 5:27:22 AM

You can write on the keyDown of any control:

        if (e.KeyCode == Keys.Enter)
        {

            if (this.GetNextControl(ActiveControl, true) != null)
            {
                e.Handled = true;
                this.GetNextControl(ActiveControl, true).Focus();

            }
        }

GetNextControl doesn't work on Vista.

To make it work with Vista you will need to use the code below to replace the this.GetNextControl...:

System.Windows.Forms.SendKeys.Send("{TAB}");

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon