31

I am using .NET 3.5 framework of VB.NET 2008.

I have some textboxes in my form. I want the tab-like behavior when my user presses ENTER on one of my textboxes. I used the following code:

Private Sub txtDiscount_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtDiscount.KeyPress
    If e.KeyChar = Microsoft.VisualBasic.ChrW(Keys.Return) Then
        SendKeys.Send("{TAB}")
        e.Handled = True
    End If
End Sub

But it doesn't work for me.

What is the solution?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Tareq
  • 1,999
  • 2
  • 28
  • 57
  • 1
    works for me, although using SendKeys wouldn't be my ideal solution – Mitch Wheat May 02 '10 at 04:23
  • when you say "But It doen't work for me.", please describe exactly what happens. we don't have crystal balls.... – Mitch Wheat May 02 '10 at 04:24
  • AcceptsReturn are set for Multiline Edit Control. But I have single Line TextBox. – Tareq May 02 '10 at 04:30
  • 2
    It is a bad idea to press Tab when a user presses Enter. You make user experience inconsistent, which may be okay for home users. Power users, however, will hate working with your software. – Victor Zakharov May 27 '13 at 14:53

16 Answers16

41

In the KeyDown Event:

 If e.KeyCode = Keys.Enter Then
       Messagebox.Show("Enter key pressed")
 end if
hawbsl
  • 15,313
  • 25
  • 73
  • 114
Dinidu Hewage
  • 2,169
  • 6
  • 40
  • 51
27

Make sure the form KeyPreview property is set to true.

Private Sub Form1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress
    If e.KeyChar = Microsoft.VisualBasic.ChrW(Keys.Return) Then
        SendKeys.Send("{TAB}")
        e.Handled = True
    End If

End Sub
13

There is no need to set the KeyPreview Property to True. Just add the following function.

Protected Overrides Function ProcessCmdKey(ByRef msg As System.Windows.Forms.Message, _
                                           ByVal keyData As System.Windows.Forms.Keys) _
                                           As Boolean

    If msg.WParam.ToInt32() = CInt(Keys.Enter) Then
        SendKeys.Send("{Tab}")
        Return True
    End If
    Return MyBase.ProcessCmdKey(msg, keyData)
End Function

Now, when you press Enter on a TextBox, the control moves to the next control.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tareq
  • 1,999
  • 2
  • 28
  • 57
  • 1
    That's almost the same as my method, except at a lower level. Did you even try my code? It does work... –  May 02 '10 at 07:16
  • 2
    It moves to the next control everytime! It needs to change your `If msg.WParam.ToInt32() = CInt(Keys.Enter) Then` into `If msg.WParam.ToInt32() = CInt(Keys.Enter) AndAlso TypeOf Me.ActiveControl Is TextBox Then` to make it only works for text boxes – genespos Jul 25 '16 at 10:27
10

I'm using VB 2010 .NET 4.0 and use the following:

Private Sub tbSecurity_KeyPress(sender As System.Object, e As System.EventArgs) Handles tbSecurity.KeyPress
    Dim tmp As System.Windows.Forms.KeyPressEventArgs = e
    If tmp.KeyChar = ChrW(Keys.Enter) Then
        MessageBox.Show("Enter key")
    Else
        MessageBox.Show(tmp.KeyChar)
    End If

End Sub

Works like a charm!

EConway
  • 131
  • 1
  • 4
7

You can use PreviewKeyDown Event

Private Sub txtPassword_PreviewKeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PreviewKeyDownEventArgs) Handles txtPassword.PreviewKeyDown
    If e.KeyCode = Keys.Enter Then
        Call btnLogin_Click(sender, e)
    End If
End Sub

Tested on VB.NET 2010

Dũng IT
  • 2,751
  • 30
  • 29
4
Private Sub SomeTextBox_KeyPress(sender As Object, e As KeyPressEventArgs) Handles SomeTextBox.KeyPress

    If Asc(e.KeyChar) = 13 Then
         MessageBox.Show("Enter pressed!")
         e.Handled = True
    End If

End Sub
tmighty
  • 10,734
  • 21
  • 104
  • 218
Alexander M.
  • 181
  • 2
  • 10
3

also can try this:

If e.KeyChar = ChrW(Keys.Enter) Then
     'Do Necessary code here
End If
John Saunders
  • 160,644
  • 26
  • 247
  • 397
Ika
  • 51
  • 2
  • -1: This is pretty much the same answer as http://stackoverflow.com/a/15994134/76337 – John Saunders Aug 23 '13 at 02:23
  • Actually, when I tried the linked answer, it wouldn't work in VS2012. Adding the 'ChrW' did the trick. It IS, however, similar to http://stackoverflow.com/a/2752456/2711474 – TesseractE Jul 22 '16 at 16:48
3

I see this has been answered, but it seems like you could avoid all of this 'remapping' of the enter key by simply hooking your validation into the AcceptButton on a form. ie. you have 3 textboxes (txtA,txtB,txtC) and an 'OK' button set to be AcceptButton (and TabOrder set properly). So, if in txtA and you hit enter, if the data is invalid, your focus will stay in txtA, but if it is valid, assuming the other txts need input, validation will just put you into the next txt that needs valid input thus simulating TAB behaviour... once all txts have valid input, pressing enter will fire a succsessful validation and close form (or whatever...) Make sense?

1

I had the same problem and I could not make this answer work on Framework 2.0 so I dug deeper.

You would have to first handle the PreviewKeyDown on the textbox so when ENTER came along you would set IsInputKey so that it could be handled by or forwarded to the keyDown event on the textbox. Like this:

Private Sub txtFiltro_PreviewKeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PreviewKeyDownEventArgs) Handles txtFiltro.PreviewKeyDown
    Select Case e.KeyCode
        Case Keys.Enter
            e.IsInputKey = True
    End Select
 End Sub

and then you would handle the event keydown on the textbox. One of the answer was on the right track but missed setting the e.IsInputKey.

Private Sub txtFiltro_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtFiltro.KeyDown
    If e.KeyCode = Keys.Enter Then
        e.handled = True
        Textbox1.Focus()
    End If
End Sub
1

Use KeyDown Event instead of KeyPress

If e.KeyCode = Keys.Enter Then
   MsgBox ("You pressed enter")
End if

Note: Make sure you don't have ACCEPT BUTTON set on your form. AcceptButton set it to 'none'

Herbert Yeo
  • 91
  • 1
  • 7
0
Private Sub BagQty_KeyPress(sender As Object, e As KeyPressEventArgs) Handles BagQty.KeyPress

        Select e.KeyChar

            Case Microsoft.VisualBasic.ChrW(Keys.Return)
                PurchaseTotal.Text = Val(ActualRate.Text) * Val(BagQty.Text)
        End Select


    End Sub
0

use this code this might help you to get tab like behaviour when user presses enter

 Private Sub TxtSearch_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TxtSearch.KeyPress
    Try
        If e.KeyChar = Convert.ToChar(13) Then
           nexttextbox.setfoucus 
        End If
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Sub
0

The following code will work.

Public Class Form1
    Private Sub TextBox1_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
        If e.KeyChar = Convert.ToChar(13) Then
            MsgBox("enter key pressd ")
        End If
    End Sub
End Clas

Public Class Form1
    Private Sub TextBox1_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown
        If e.KeyCode = Keys.Enter Then
            MsgBox("enter key pressd ")
        End If
    End Sub
End Class
Pang
  • 9,564
  • 146
  • 81
  • 122
0

Use this code it will work OK. You shall click on TextBox1 and then go to event and select Keyup and double click on it. You wil then get the lines for the SUB.

Private Sub TextBox1_KeyUp(ByVal sender As System.Object, ByVal e As      
System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyUp
    If e.KeyCode = Keys.Enter Then
        MsgBox("Fel lösenord")

    End If
End Sub
  • So 7 years later a suggestion with a Swedish Message ;) Maybe match his issue? – mplungjan Mar 05 '17 at 10:13
  • This will be better with a KeyDown, otherwise when you press Enter on the keyboard to dismiss it, and you get the same message alert, and you're stuck in a look. – vr_driver Feb 28 '18 at 04:03
0

I have test this code on Visual Studio 2019

Its working superb

Just Paste it into you form code

it will work on all textboxs on same form

Protected Overrides Function ProcessCmdKey(ByRef msg As System.Windows.Forms.Message, ByVal keyData As System.Windows.Forms.Keys) As Boolean
    Dim keyCode As Keys = CType(msg.WParam, IntPtr).ToInt32
    Const WM_KEYDOWN As Integer = &H100

    If msg.Msg = WM_KEYDOWN AndAlso keyCode = Keys.Enter _
     AndAlso Me.ActiveControl.GetType.Name = "TextBox" Then
        Me.SelectNextControl(Me.ActiveControl, True, True, False, True)
        Return True

    End If
    Return MyBase.ProcessCmdKey(msg, keyData)


End Function
Adnan Zaheer
  • 392
  • 3
  • 13
0

Someone suggested "PreviewKeyDown". Given this code and results entering '1 2 tab 3' one can see that "PreviewKeyDown" can be used only to redirect a key (that would normally not pass thru "KeyDown/Press/Up") to it, so you can act upon it. Note that the key is NOT added to "Text". You can only remember having seen the key in Preview and then act upon this saved information in KeyDown/Up/Press

Dim eDotIsInputKey As Boolean = False
Private Sub AkteNr_TextChanged(sender As Object, e As EventArgs) Handles AkteNr.TextChanged
    Debug.WriteLine("ch !" + AkteNr.Text + "!")
End Sub
Private Sub AkteNr_PreviewKeyDown(sender As Object, e As PreviewKeyDownEventArgs) Handles AkteNr.PreviewKeyDown
    If e.KeyCode = Keys.Tab Then
        e.IsInputKey = True
    End If
    eDotIsInputKey = e.IsInputKey
    Debug.WriteLine("pr " + CStr(e.KeyCode) + " " + CStr(e.IsInputKey))
End Sub
Private Sub AkteNr_KeyDown(sender As Object, e As KeyEventArgs) Handles AkteNr.KeyDown
    Debug.WriteLine("kd " + CStr(e.KeyCode) + " " + CStr(eDotIsInputKey))
End Sub

Result if entering 1 then 2 then tab then 3:

pr 49 False
kd 49 False
ch !1!
pr 50 False
kd 50 False
ch !12!
pr 9 True
kd 9 True
pr 51 False
kd 51 False
ch !123!
Martin
  • 1,430
  • 10
  • 19