How To Make ENTER Key Move Focus Like TAB Key for VB Controls

This article was previously published under Q142816
This article has been archived. It is offered "as is" and will no longer be updated.
SUMMARY
You can cause the ENTER key to move the focus to the control with thenext higher TabIndex property value, as the TAB key does.

However, using the ENTER key to move the focus does not follow recommendedMicrosoft Windows-based application design guidelines. The ENTER key shouldbe used to process the default command or to process entered information,not to move the focus.
MORE INFORMATION
You can detect when the user presses the ENTER key from the KeyPress eventprocedure by checking to see if the KeyAscii parameter is the charactercode for the ENTER key (13). Then you can move the focus to the nextcontrol in the TabIndex order with SendKeys "{tab}." You can move the focusto the previous control with SendKeys "+{tab}."

This technique works with most kinds of controls. It does not work withcommand button controls, because command buttons do not receive theKeyPress event when you press the ENTER key.

Step-by-Step Example

  1. Start a new project in Visual Basic. Form1 is created by default.
  2. Add two text boxes (Text1 and Text2) to Form1.
  3. Add the following code to the Text1 KeyPress procedure:
          Private Sub Text1_KeyPress (KeyAscii As Integer)         If KeyAscii = 13 Then  ' The ENTER key.            SendKeys "{tab}"    ' Set the focus to the next control.            KeyAscii = 0        ' Ignore this key.         End If      End Sub						
  4. Add the following code to the Text2 KeyPress procedure:
          Private Sub Text2_KeyPress (KeyAscii As Integer)         If KeyAscii = 13 Then  ' The ENTER key.            SendKeys "{tab}"    ' Set the focus to the next control.            KeyAscii = 0        ' Ignore this key.         End If      End Sub						
  5. Press the F5 key to run the program. When you press the ENTER key, the focus moves between the two controls.
kbVBp400 kbVBp500 kbVBp600 kbControl kbVBp kbdsd kbDSupport
Properties

Article ID: 142816 - Last Review: 12/04/2015 13:04:53 - Revision: 2.1

Microsoft Visual Basic 5.0 Learning Edition, Microsoft Visual Basic 6.0 Learning Edition, Microsoft Visual Basic 5.0 Professional Edition, Microsoft Visual Basic 6.0 Professional Edition, Microsoft Visual Basic 5.0 Enterprise Edition, Microsoft Visual Basic 6.0 Enterprise Edition, Microsoft Visual Basic 4.0 Professional Edition, Microsoft Visual Basic 4.0 Professional Edition, Microsoft Visual Basic 4.0 16-bit Enterprise Edition, Microsoft Visual Basic 4.0 32-Bit Enterprise Edition

  • kbnosurvey kbarchive kbhowto KB142816
Feedback