Site hosted by Angelfire.com: Build your free website today!

Alternative to SendKeys to change TextBox Focus

How many times you wanted to change the focus from a text box control to the next control in tab index with ENTER key?
You, for sure, could use this code
Private Sub Text1_KeyPress(KeyAscii As Integer)
If KeyAscii = 13 Then
    KeyAscii = 0
    Sendkeys "{TAB}"
End If
End Sub
SendKeys has strange behaviour sometimes (to me, from time to time, disables NumLock key)
An alternative is the following that allows you to use any event (KeyPress, KeyDown, KeyUp but taking care to change keyascii to keycode in the last two ones :) to change the focus every time you push ENTER key inside TextBox control.
Private Declare Sub keybd_event Lib "user32.dll" (ByVal bVk As Byte, ByVal bScan As Byte, _
             ByVal dwFlags As Long, ByVal dwExtraInfo As Long)

Const VK_TAB = &H9
Const KEYEVENTF_KEYUP = &H2

Private Sub Text1_KeyPress(KeyAscii As Integer)
If KeyAscii = 13 Then
    KeyAscii = 0
    keybd_event VK_TAB, 0, 0, 0  ' Press
    keybd_event VK_TAB, 0, KEYEVENTF_KEYUP, 0 ' Up
End If
End Sub
You could easily use it in your entire form, if you manage those events but from Form instead textbox control, setting KeyPreview property to True.

Happy programming.


©2001 - Richie Simonetti