# Visual Basic > Visual Basic 6 and Earlier >  SendKeys causes NumLock to turn off

## fishg92

When using SendKeys to turn an Enter keystroke into a Tab keystroke (SendKeys "{TAB}"), NumLock will briefly turn off. When users are keying rapidly, they enter data into a field and hit the Enter key. The focus moves to the next field, but if they enter something else on the numeric keypad, it is interpreted as PageUp, PageDown, or whatever the number key represents without NumLock.

There is a database call on LostFocus that may take 1 or 2 seconds, and NumLock will not turn back on until this operation completes. However, if I actually use the Tab key, this delay still occurs, but NumLock will not turn off.

I have tried using the Wait option after SendKeys, but it does not make a difference. I have also inserted DoEvents at various places without success.

This happens only on Windows NT and Windows 2000. Windows 95 is not affected, and I have not tried it on 98 or XP.

----------


## MerrionComputin

This is a know issue with Sendkeys - use this fix:


VB Code:
'\\ For saving and resetting caps/scroll and numlock keys
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 Const VK_NUMLOCK = &H90
Private Const VK_SCROLL = &H91
Private Const VK_CAPITAL = &H14
Private Const KEYEVENTF_EXTENDEDKEY = &H1
Private Const KEYEVENTF_KEYUP = &H2
 Public Sub SafeSendkeys(ByVal keys As String, Optional bWait As Variant)
 '\\ Save the special keys' state...
Dim keysBefore(0 To 255) As Byte
Dim keysAfter(0 To 255) As Byte
 Call GetKeyboardState(keysBefore(0))
 If IsMissing(bWait) Then
    Call SendKeys(keys, False)
Else
    Call SendKeys(keys, CBool(bWait))
End If
 Call GetKeyboardState(keysAfter(0))
'\\ "Press" numlock if it has changed
If keysBefore(VK_NUMLOCK) <> keysAfter(VK_NUMLOCK) Then
    '\\ key down
    Call keybd_event(VK_NUMLOCK, &H45, KEYEVENTF_EXTENDEDKEY, 0)
    '\\ key up = 1 key press
    Call keybd_event(VK_NUMLOCK, &H45, KEYEVENTF_EXTENDEDKEY Or KEYEVENTF_KEYUP, 0)
End If
'\\ "Press" caps if it has changed
If keysBefore(VK_CAPITAL) <> keysAfter(VK_CAPITAL) Then
    '\\ key down
    Call keybd_event(VK_CAPITAL, &H45, KEYEVENTF_EXTENDEDKEY, 0)
    '\\ key up = 1 key press
    Call keybd_event(VK_CAPITAL, &H45, KEYEVENTF_EXTENDEDKEY Or KEYEVENTF_KEYUP, 0)
End If
'\\ "Press" scroll lock if it has changed
If keysBefore(VK_SCROLL) <> keysAfter(VK_SCROLL) Then
    '\\ key down
    Call keybd_event(VK_SCROLL, &H45, KEYEVENTF_EXTENDEDKEY, 0)
    '\\ key up = 1 key press
    Call keybd_event(VK_SCROLL, &H45, KEYEVENTF_EXTENDEDKEY Or KEYEVENTF_KEYUP, 0)
End If
 End Sub

Hope this helps,
   Duncan

----------


## Ursalain

Thanks a lot for this very useful VBA Sub !

----------

