Alex Rivera | Logout

Detecting Enter keypress on VB.NET

Asked 2010-05-02T04:15:08.993
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?

Edit
Report

2 Answers

42

In the KeyDown Event:

 If e.KeyCode = Keys.Enter Then
       Messagebox.Show("Enter key pressed")
 end if
answered 2013-04-13T23:41:31.810
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.

answered 2010-05-02T06:43:26.610

Your Answer