Link to home
Start Free TrialLog in
Avatar of Juan Velasquez
Juan VelasquezFlag for United States of America

asked on

How do I convert Enter Key to Tab Key

I am using the attached code to intercept the enter key so that it works like a tab key. I works find for text, list boxes, and combo boxes.  However when the focus is moved to a button, the enter key reverts to being a enter key.  What event of a button, do I have to hook this code to
Private Sub nametxt_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles dgvStagingMetricsList.KeyDown, _
    txtMetric.KeyDown, txtSelectedFile.KeyDown, txtTechnology.KeyDown, txtUnits.KeyDown

        If e.KeyCode = Keys.Enter Then
            Me.SelectNextControl(Me.ActiveControl, True, True, True, True)
        End If

    End Sub

Open in new window

Avatar of yjchong514
yjchong514
Flag of United States of America image

Private Sub nametxt_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles nametxt.KeyDown, gendertxt.KeyDown

    If e.KeyCode = Keys.Enter Then
         Me.SelectNextControl(Me.ActiveControl, True, True, True, True)
    End If
    End Sub

You can use the same event on all textboxes by adding the control.Keydown event from the Handles keyword of that event.

'This will stop the chime sound when Enter is press.
If e.KeyCode = Keys.Enter Then

e.SuppressKeyPress = True
Me.SelectNextControl(Me.ActiveControl, True, True, True, True)
End If    

Set the KeyPreview attribute on your form to True, then use the KeyPress event at your form level to detect the Enter key.
Avatar of Mike Tomlinson
I would do it this way instead...  =)
(NO KeyPreview needed)
Public Class Form1

    Protected Overrides Function ProcessCmdKey(ByRef msg As System.Windows.Forms.Message, ByVal keyData As System.Windows.Forms.Keys) As Boolean
        Select Case keyData
            Case Keys.Enter
                    SendKeys.Send("{Tab}")
                    Return True

        End Select
        Return MyBase.ProcessCmdKey(msg, keyData)
    End Function

End Class

Open in new window

Avatar of Juan Velasquez

ASKER

Hello Idle Mind,
I understand the code except for the return portion of it. Could you explain where it is being returned to .  I'm new to vb.net and while the code works, I would like to know how that section works.  This way, I'm not cutting and pasting code with no understanding of how it works.  Thanks again.
ASKER CERTIFIED SOLUTION
Avatar of Mike Tomlinson
Mike Tomlinson
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks for the explanation.  That made things clearer