Solved

Error when using function Sendkeys "{TAB}"

Posted on 2004-04-22
6
623 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
Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

 

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

Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Article by: Martin
Here are a few simple, working, games that you can use as-is or as the basis for your own games. Tic-Tac-Toe This is one of the simplest of all games.   The game allows for a choice of who goes first and keeps track of the number of wins for…
I was working on a PowerPoint add-in the other day and a client asked me "can you implement a feature which processes a chart when it's pasted into a slide from another deck?". It got me wondering how to hook into built-in ribbon events in Office.
Get people started with the process of using Access VBA to control Excel using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Excel. Using automation, an Access application can laun…
Get people started with the utilization of class modules. Class modules can be a powerful tool in Microsoft Access. They allow you to create self-contained objects that encapsulate functionality. They can easily hide the complexity of a process from…

776 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