Until now I've been replacing Enter key behaviour in controls (in base classes) with Tab key behaviour with the following code in the keypress event handler :

       If e.KeyChar = Chr(13) Then
            SendKeys.Send(vbTab)
            e.Handled = True
        End If

Although it's worked for me until now, I have serious doubts about the (thread)safety of this approach.

Recommended Answers

All 4 Replies

I think a better way to do this would be

Private Sub TextBox1_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
    If e.KeyChar = vbCr Then
        Me.SelectNextControl(Me.ActiveControl, True, True, True, True)
        e.Handled = True
    End If
End Sub

Private Sub TextBox2_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox2.KeyPress
    If e.KeyChar = vbCr Then
        Me.SelectNextControl(Me.ActiveControl, True, True, True, True)
        e.Handled = True
    End If
End Sub

Or even

Private Sub TextBox1_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress, TextBox2.KeyPress
    If e.KeyChar = vbCr Then
        Me.SelectNextControl(Me.ActiveControl, True, True, True, True)
        e.Handled = True
    End If
End Sub

The last four parameters are

forward    
    true to move forward in the tab order; false to move backward
tabStopOnly  
    true to ignore the controls with the TabStop property set to false; otherwise, false.
nested
    true to include nested child controls; otherwise, false.
wrap
    true to continue searching from the first control in the tab order after the last control has been reached; otherwise, false.

Thank you very much.

I hesitated to implement this in this way because it assumes thet the behaviour is always to go to the next control.

Exceptions in point are the datagridview, and listviews.

But those need a specific approach with my approach as well because the sent character never hits eventhanling unless the control is exited.

I will follow your advice.

You could always specify a specific action for each handler if you use the first approach.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.