Microsoft KB Archive/161247

= Microsoft Knowledge Base =

HOWTO: Make ENTER Key Move Focus Like TAB Key for VB Control
Last reviewed: July 15, 1997

Article ID: Q161247

The information in this article applies to:


 * Microsoft Visual Basic Learning, Professional, and Enterprise Editions, for Windows, version 5.0

SUMMARY
You can cause the ENTER key to move the focus to the control with the next higher TabIndex property value just as the TAB key does.

However, using the ENTER key to move the focus does not follow recommended Microsoft Windows-based application design guidelines. The ENTER key should be 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 event procedure by checking to see if the KeyAscii parameter is the character code for the ENTER key (13). Then you can move the focus to the next control in the TabIndex order with SendKeys "{tab}". You can move the focus to the previous control with SendKeys "+{tab}".

This technique works with most kinds of controls. It does not work with CommandButton controls, however, because CommandButtons do not receive the KeyPress event when you press the ENTER key.

Steps to Create Example Program
 Start Visual Basic, or, if Visual Basic is running, create a new project. Form1 is created by default. Add two textboxes, Text1 and Text2, to Form1.  Copy and paste the following code into the Form1 code window: 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 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  Press the F5 key to run the program. When you press the ENTER key, the focus moves between the two controls.

Keywords         : PrgCtrlsStd vb5all vb5howto VBKBCtrl_VBKBStd kbusage kbhowto Version          : 5.00 Platform         : WINDOWS Issue type       : kbhowto