How to make Enter on a TextBox act as TAB button

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}");

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);
}

You don't need to make an "enter event handler"

All you need to do is make a "central" KeyDown event:

example

private void General_KeyDown(object sender, KeyPressEventArgs e)
 {
 if (e.KeyCode == Keys.Enter)
        {

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

Then all you have to do is go to designer select all textboxes you wish to cycle through with EnterKey (select them by holding down Ctrl and clicking on textbox with the mouse) then go to Events(thunder like button), search Keydown event and type inside General_KeyDown. Now all your selected Textboxes will have the same keydown event :) This makes everything muuuuch much easier, cause imagine a form with 100 textboxes and you want to cycle through all with enter.... making an apart event for each texbox is... well not a proper way to make a program, it ain't neat. Hope it helped!!

Blockquote

Tags:

C#

.Net

Winforms