If you want to "capture" the key and halt its processing by other apps, set the Handled property to true in your event handler. To add handlers in VB.Net, you use AddHandler and AddressOf . The functions KeyDown and KeyUp would look like this.
The easiest way to open the Visual Basic editor is to use the keyboard shortcut – ALT + F11 (hold the ALT key and press the F11 key). As soon as you do this, it will open a separate window for the Visual Basic editor.
The keydown event is fired when a key is pressed. Unlike the keypress event, the keydown event is fired for all keys, regardless of whether they produce a character value. The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered.
In the KeyDown Event:
If e.KeyCode = Keys.Enter Then
Messagebox.Show("Enter key pressed")
end if
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
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With