Using Enter Key as a Tab
A common question on the forums is how to use the Enter key instead of the Tab key to move through the controls on a Windows form. One common approach is to use SendKeys to send a Tab. But here is another option.
NOTE: To use this technique, set the KeyPreview property of the form to True.
In C#:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
Control nextControl ;
if (e.KeyCode == Keys.Enter)
{
nextControl = GetNextControl(ActiveControl, !e.Shift);
if (nextControl == null)
nextControl = GetNextControl(null, true);
nextControl.Focus();
e.SuppressKeyPress = true;
}
}
In VB:
Private Sub Form1_KeyDown(ByVal sender As Object,
ByVal e As System.Windows.Forms.KeyEventArgs) _
Handles Me.KeyDown
Dim nextControl As Control
If e.KeyCode = Keys.Enter Then
nextControl = GetNextControl(ActiveControl, Not e.Shift)
If nextControl Is Nothing Then
nextControl = GetNextControl(Nothing, True)
End If
nextControl.Focus()
e.SuppressKeyPress = True
End If
End Sub
This code first checks the key that was pressed down and if it was the Enter key, processes it.
It uses the GetNextControl method to find the next control in the tab order. It checks the Shift key and if the Shift key is also pressed, GetNextControl finds the prior key in the tab order.
If GetNextControl does not find another control (because it runs into the end of the tab order), it calls GetNextControl again passing in a null to start back at the other end of the tab order.
For example, if you have four TextBoxes: 1,2,3,4, pressing the Enter key will move you from 1 to 2 to 3 to 4 and then back to 1. Pressing Shift + Enter will move you from 4 to 3 to 2 to 1.
Use this technique any time your users want to use the Enter key instead of the Tab key to move through the controls on a Windows form.
Hope this helps.
acharya — January 31, 2013 @ 2:34 am
this is not working reply me with Example on sunil.ach87@gmail.com