Saturday, December 17, 2005

How stupid I am

Tab is the preferred key used to move from one object to the next in a form. However, some users may prefer to use the Enter key instead. To make that possible in a Visual Basic form I made this plan:
Private Sub Form_Load()
Me.KeyPreview = True ' so the form receives keystrokes before the objects
End Sub

Private Sub Form_KeyPress(KeyAscii As Integer)
If KeyAscii = 13 Then
  ' find out which object has the focus
  ' find the tab index to the object
  ' increase the tab index by 1
  ' find the object with that tab index
  ' give the object focus
  KeyAscii = 0       ' Ignore this key.
End If
End Sub
A quick Google Group search made me kick myself behind. The five commented lines above can be replaced by one single instruction:
SendKeys "{tab}"   ' Set focus to next control.
Translated: let the Enter key pretend it is a Tab key.

No comments: