reza
reza

Reputation: 155

How to turn on or off the Caps Lock key in VB6?

How to turn on or off the Caps Lock key in Visual Basic6 ?

Upvotes: 1

Views: 5511

Answers (2)

Ilya Kurnosov
Ilya Kurnosov

Reputation: 3220

Since keybd_event function has been superseded, SendInput (MSDN) is a way to go. BTW, If you're about to do something serious with keyboard in VB6, make sure to check Carl E. Peterson's article and code here: http://vb.mvps.org/samples/SendInput/

To set CapsLock state one may use the following code (optionally put into standard module). SetCapsLockState(True) enables CapsLock, and SetCapsLockState(False) disables it.

Option Explicit

Private Declare Function GetKeyState Lib "user32" _
    (ByVal nVirtKey As Long) As Integer
Private Declare Function MapVirtualKey Lib "user32" _
    Alias "MapVirtualKeyA" _
    (ByVal uCode As Long, ByVal uMapType As Long) As Long
Private Declare Function SendInput Lib "user32" _
    (ByVal nInputs As Long, pInputs As Any, ByVal cbSize As Long) As Long

Private Type KeyboardInput       '   typedef struct tagINPUT {
   dwType As Long                '     DWORD type;
   wVK As Integer                '     union {MOUSEINPUT mi;
   wScan As Integer              '            KEYBDINPUT ki;
   dwFlags As Long               '            HARDWAREINPUT hi;
   dwTime As Long                '     };
   dwExtraInfo As Long           '   }INPUT, *PINPUT;
   dwPadding As Currency         '
End Type

'SendInput constants
Private Const INPUT_KEYBOARD As Long = 1
Private Const KEYEVENTF_KEYUP As Long = 2

Private Const VK_CAPITAL = &H14

Public Function CapsLock() As Boolean
   ' Determine whether CAPSLOCK key is toggled on.
   CapsLock = CBool(GetKeyState(VK_CAPITAL) And 1)
End Function

Public Sub SetCapsLockState(bEnabled As Boolean)
    'CapsLock is already in desired state. Nothing to do.
    If CapsLock = bEnabled Then Exit Sub

    PressCapsLock
End Sub

Private Sub PressCapsLock()
    GenerateKeyboardEvent VK_CAPITAL, 0
    GenerateKeyboardEvent VK_CAPITAL, KEYEVENTF_KEYUP
End Sub

Private Sub GenerateKeyboardEvent(VirtualKey As Long, Flags As Long)
    Dim kevent As KeyboardInput

    With kevent
        .dwType = INPUT_KEYBOARD
        .wScan = MapVirtualKey(VirtualKey, 0)
        .wVK = VirtualKey
        .dwTime = 0
        .dwFlags = Flags
    End With
    SendInput 1, kevent, Len(kevent)
End Sub

One can call it from a form module like this:

Option Explicit

Private Sub cmdCapsLockOff_Click()
    SetCapsLockState False
End Sub

Private Sub cmdCapsLockOn_Click()
    SetCapsLockState True
End Sub

Private Sub cmdShowState_Click()
    MsgBox "CapsLock is " & IIf(CapsLock, "ON", "OFF")
End Sub

Upvotes: 4

Arvo
Arvo

Reputation: 10570

MS KB article 177674: How To Toggle the NUM LOCK, CAPS LOCK, and SCROLL LOCK Keys

Upvotes: 2

Related Questions