Error when using function Sendkeys "{TAB}"

To help users using key ENTER when working on forms, I usually using function SendKeys (code below)

Private Sub Form1_KeyDown(KeyCode As Integer, Shift As Integer)
    If KeyCode = 13 Then
            SendKeys "{TAB}"
            KeyCode = 0
    End If
End Sub

Somestimes, function works well; sometimes, it does not work, and users must press {TAB} key to move to next input field

I don't understand where must to focust ? Code ? Environment ? or other ?
giangltAsked:
Who is Participating?
 
mimilConnect With a Mentor Commented:
I also had issues with sendkeys, among other was the fact that in some case, the keybord state will change (Numlock Off when it was on ...)

I can't remember all the details, but I read that it was not exactly a good idea to use this function.

Currently I use the following code to do the job:

**** To be added in a module (basSendKey for ex)*****
'******** Code Start ***********
      ' Declare Type for API call:
      Private Type OSVERSIONINFO
        dwOSVersionInfoSize As Long
        dwMajorVersion As Long
        dwMinorVersion As Long
        dwBuildNumber As Long
        dwPlatformId As Long
        szCSDVersion As String * 128   '  Maintenance string for PSS usage
      End Type

      ' API declarations:
      Private Declare Function GetVersionEx Lib "Kernel32" _
         Alias "GetVersionExA" _
         (lpVersionInformation As OSVERSIONINFO) As Long

      Private Declare Sub keybd_event Lib "user32" _
         (ByVal bVk As Byte, _
          ByVal bScan As Byte, _
          ByVal dwflags As Long, ByVal dwExtraInfo As Long)

      Private Declare Function GetKeyboardState Lib "user32" _
         (pbKeyState As Byte) As Long

      Private Declare Function SetKeyboardState Lib "user32" _
         (lppbKeyState As Byte) As Long

      ' Constant declarations:
      Const VK_NUMLOCK = &H90
      Const VK_SCROLL = &H91
      Const VK_CAPITAL = &H14
      Const KEYEVENTF_EXTENDEDKEY = &H1
      Const KEYEVENTF_KEYUP = &H2
      Const VER_PLATFORM_WIN32_NT = 2
      Const VER_PLATFORM_WIN32_WINDOWS = 1

Function IsCapsLockOn() As Boolean
        Dim o As OSVERSIONINFO

        o.dwOSVersionInfoSize = Len(o)
        GetVersionEx o
        Dim keys(0 To 255) As Byte
        GetKeyboardState keys(0)
        IsCapsLockOn = keys(VK_CAPITAL)
End Function

Sub ToggleCapsLock()
        Dim o As OSVERSIONINFO

        o.dwOSVersionInfoSize = Len(o)
        GetVersionEx o
        Dim keys(0 To 255) As Byte
        GetKeyboardState keys(0)

        If o.dwPlatformId = VER_PLATFORM_WIN32_WINDOWS Then  '=====Win95
        'Toggle capslock
            keys(VK_CAPITAL) = Abs(Not keys(VK_CAPITAL))
            SetKeyboardState keys(0)
        ElseIf o.dwPlatformId = VER_PLATFORM_WIN32_NT Then   '=====WinNT
          'Simulate Key Press>
            keybd_event VK_CAPITAL, &H45, KEYEVENTF_EXTENDEDKEY Or 0, 0
          'Simulate Key Release
            keybd_event VK_CAPITAL, &H45, KEYEVENTF_EXTENDEDKEY _
               Or KEYEVENTF_KEYUP, 0
        End If
End Sub

Function IsNumLockOn() As Boolean
        Dim o As OSVERSIONINFO
       
        o.dwOSVersionInfoSize = Len(o)
        GetVersionEx o
        Dim keys(0 To 255) As Byte
        GetKeyboardState keys(0)
        IsNumLockOn = keys(VK_NUMLOCK)
End Function

Sub ToggleNumLock()
        Dim o As OSVERSIONINFO
               
        o.dwOSVersionInfoSize = Len(o)
        GetVersionEx o
        Dim keys(0 To 255) As Byte
        GetKeyboardState keys(0)

          If o.dwPlatformId = VER_PLATFORM_WIN32_WINDOWS Then  '=====Win95
                keys(VK_NUMLOCK) = Abs(Not keys(VK_NUMLOCK))
                SetKeyboardState keys(0)
          ElseIf o.dwPlatformId = VER_PLATFORM_WIN32_NT Then   '=====WinNT
          'Simulate Key Press
            keybd_event VK_NUMLOCK, &H45, KEYEVENTF_EXTENDEDKEY Or 0, 0
          'Simulate Key Release
            keybd_event VK_NUMLOCK, &H45, KEYEVENTF_EXTENDEDKEY _
               Or KEYEVENTF_KEYUP, 0
          End If
       
End Sub

Function IsScrollLockOn()
        Dim o As OSVERSIONINFO
       
        o.dwOSVersionInfoSize = Len(o)
        GetVersionEx o
        Dim keys(0 To 255) As Byte
        GetKeyboardState keys(0)
        IsScrollLockOn = keys(VK_SCROLL)
End Function

Sub ToggleScrollLock()
        Dim o As OSVERSIONINFO
       
        o.dwOSVersionInfoSize = Len(o)
        GetVersionEx o
        Dim keys(0 To 255) As Byte
        GetKeyboardState keys(0)
        If o.dwPlatformId = VER_PLATFORM_WIN32_WINDOWS Then  '=====Win95
            keys(VK_SCROLL) = Abs(Not keys(VK_SCROLL))
            SetKeyboardState keys(0)
        ElseIf o.dwPlatformId = VER_PLATFORM_WIN32_NT Then   '=====WinNT
            'Simulate Key Press
            keybd_event VK_SCROLL, &H45, KEYEVENTF_EXTENDEDKEY Or 0, 0
            'Simulate Key Release
            keybd_event VK_SCROLL, &H45, KEYEVENTF_EXTENDEDKEY Or KEYEVENTF_KEYUP, 0
        End If
End Sub

Sub mySendKeys(sKeys As String, Optional bWait As Boolean = False)
Dim bNumLockState As Boolean
Dim bCapsLockState As Boolean
Dim bScrollLockState As Boolean
    bNumLockState = IsNumLockOn()
    bCapsLockState = IsCapsLockOn()
    bScrollLockState = IsScrollLockOn()
    SendKeys sKeys, bWait
    If IsNumLockOn() <> bNumLockState Then
        ToggleNumLock
    End If
    If IsCapsLockOn() <> bCapsLockState Then
        ToggleCapsLock
    End If
    If IsScrollLockOn() <> bScrollLockState Then
        ToggleScrollLock
    End If
End Sub

Function fSendKeys(sKeys As String, Optional bWait As Boolean = False)
' Function to make it callable from macros
    mySendKeys sKeys, bWait
End Function
'******** Code End ***********


to use:
fSendKeys vbTab

Maybe it can help.
0
 
zzzzzoocCommented:
Use KeyPreview=True to have all Key-Presses raised to Form-Level. Then use the KeyPress event.

Form1:
---------------
Private Sub Form_KeyPress(KeyAscii As Integer)
    If KeyAscii = 13 Then
        Call SendKeys("{TAB}")
        KeyAscii = 0
    End If
End Sub
Private Sub Form_Load()
    Me.KeyPreview = True
End Sub
0
 
OHDev2004Commented:
Hi gianglt , why dont you object.setfocus

like

Private Sub Form1_KeyDown(KeyCode As Integer, Shift As Integer)
    If KeyCode = 13 Then
       object.Setfocus
    End If
End Sub

then you can ask in a routine which object has focus and which object is the next you want to send the focus to


><><><><><><><========================

another solution : give all the objects you want to change focus from/ to a numbering TAG
what i mean is in every object.Tag give it a number in an ascending range like
first dimense a public integer
dim ActivObj as integer

form_Load()
textbox1.tag=1
textbox2.tag=2
textbox3.tag=3
'etc
end sub


'then in every Object_Gotfocus(...) event write this code
private sub text1_Gotfocus(........)
ActivObj =text1.tag
end sub


'then in every Object_Keydown(....) event write this code
Private Sub text1_KeyDown(KeyCode As Integer, Shift As Integer)
 If KeyCode = 13 Then call  GotoNextObject()
end sub

Private Function GotoNextObject()
Dim x As Integer
For x = 0 To Form.Controls.Count - 1
If Me.Control(x).Tag = ActivObj + 1 Then Me.Controls(x).SetFocus: Exit For
Next x
end function
===========================
OHDev
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
giangltAuthor Commented:
I know that must using command  KeyPreview=True in form
The problem is when using the same code on different machine and run program (in design environment), sometimes event raise, but somtimes it doesn't.
When I run program in debug mode, event always raise.
Do anyone have seen it
0
 
OHDev2004Commented:
did you try the routine i used above ?? its not the traditional way :) but'll work
0
 
giangltAuthor Commented:
To OHDev2004 :
I think that I can't follow you, because this way takes off from us a lot of times to set tags for controls
0
All Courses

From novice to tech pro — start learning today.