Free Information Technology Magazines and eBooks

Friday, February 06, 2009

VB.NET: Use Enter key to move focus to next control like a TAB key

In Vb6, to mimic tab key we use the command SendKeys "{TAB}". For example if we want return or enter key to use like a TAB key then we do the following:

//set forms KEYPREVIEW = TRUE
Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
If KeyCode = vbKeyReturn Then
SendKeys "{TAB}"
End If
End Sub


But on VB.NET this won't work and not practical. Instead we can utilize the SelectNextControl of the current active control as shown below:

Private Sub nametxt_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles nametxt.KeyDown, gendertxt.KeyDown, agetxt.KeyDown
If e.KeyCode = Keys.Enter Then
Me.SelectNextControl(Me.ActiveControl, True, True, True, True)
End If
End Sub


You can use the same event on all textboxes by adding the control.Keydown event from the Handles keyword of that event.

Private Sub nametxt_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles nametxt.KeyDown, gendertxt.KeyDown, agetxt.KeyDown //add any textbox here to use this event


That's all! your form's Enter key should now mimic the TAB key. Hope this help anyone.

5 comments:

Anonymous said...

This works great, but now I get an event chime when I press Enter. How can I prevent the event chime from playing?

Fryan Valdez said...

To prevent the beep sound. Add the highlighted line below.

If e.KeyCode = Keys.Enter Then

e.SuppressKeyPress = True
Me.SelectNextControl(Me.ActiveControl, True, True, True, True)
End If

Sandesh said...

This works Perfect

Anonymous said...

wow this is great
thanks for the codes..it help me alot

~vdj

Psynister said...

Granted, it's a few years old now, but I didn't know how to do this until I found you today so surely I'm not the only one.

You can also get rid of the sound by using: e.handled = True

Many, many thanks for this post as I dug through several pages worth of links on Google that didn't work until I found you.