Solved

Error when using function Sendkeys "{TAB}"

Posted on 2004-04-22
6
618 Views
Last Modified: 2008-02-01
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 ?
0
Comment
Question by:gianglt
6 Comments
 
LVL 17

Expert Comment

by:zzzzzooc
ID: 10895261
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
 
LVL 7

Expert Comment

by:OHDev2004
ID: 10895318
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
 
LVL 1

Accepted Solution

by:
mimil earned 100 total points
ID: 10895792
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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

Author Comment

by:gianglt
ID: 10896838
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
 
LVL 7

Expert Comment

by:OHDev2004
ID: 10906599
did you try the routine i used above ?? its not the traditional way :) but'll work
0
 

Author Comment

by:gianglt
ID: 10915717
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

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Introduction While answering a recent question (http://www.experts-exchange.com/Q_27402310.html) in the VB classic zone, I wrote some VB code in the (Office) VBA environment, rather than fire up my older PC.  I didn't post completely correct code o…
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
As developers, we are not limited to the functions provided by the VBA language. In addition, we can call the functions that are part of the Windows operating system. These functions are part of the Windows API (Application Programming Interface). U…
This lesson covers basic error handling code in Microsoft Excel using VBA. This is the first lesson in a 3-part series that uses code to loop through an Excel spreadsheet in VBA and then fix errors, taking advantage of error handling code. This l…

759 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now