Vb.net – Enter and Tab sends focus to next textbox

textboxvb.netwinforms

I had made a class by inheriting the system textbox shown in following code.

Public Class textboxex

Inherits TextBox
Private Sub TextBoxEx_Return(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown

    If e.KeyCode = Keys.Enter Then
        SendKeys.Send("{TAB}")
        Me.Text = Me.Text.ToUpper  'To change the text to upper case when it leaves focus.(working fine)
    End If
End Sub

Now problem is when I press Tab key, it doesn't enter the if condition.
Probably it would not because I havn't given if condition for tab key.

But I after I changed the if condition by adding e.keycode = keys.Tab and pressing tab key, it won't do the Uppercase of the letters but enter does it fine. The updated code shown below.

If e.KeyCode = Keys.Enter or e.KeyCode = Keys.Tab Then
        SendKeys.Send("{TAB}")
        Me.Text = Me.Text.ToUpper 'doesn't work when tab is pressed | enter works fine
    End If

So this is my problem, help me plox…!!!!!!!

Best Answer

To make Enter work like Tab

You can override ProcessCmdKey method and check if the key is Enter then, send a Tab key or ussing SelectNextControl, move focus to next control:

Public Class MyTextBox
    Inherits TextBox
    Protected Overrides Function ProcessCmdKey(ByRef msg As Message, keyData As Keys) _
        As Boolean
        If (keyData = Keys.Enter) Then
            SendKeys.Send("{TAB}")
            'Parent.SelectNextControl(Me, True, True, True, True)
            Return True
        End If
        Return MyBase.ProcessCmdKey(msg, keyData)
    End Function
End Class
Related Topic