Detecting Enter keypress on VB.NET
Detecting Enter keypress on VB.NET
Question
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?
Accepted Answer
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.
Popular Answer
In the KeyDown Event:
If e.KeyCode = Keys.Enter Then
Messagebox.Show("Enter key pressed")
end if
Read more... Read less...
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
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!
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
also can try this:
If e.KeyChar = ChrW(Keys.Enter) Then
'Do Necessary code here
End If
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?