Friday, April 29, 2011

Programmically toggling capslock button

VB.NET doesn’t contain any function through which we can On/Off capslock button in the keyboard. VB.NET has one function called My.Computer.Keyboard.CapsLock but it is readonly so we cannot change it. Capslock key also cannot be toggled by using SendKeys,Send() method. So only way to toggle the capslock key is by using WinAPIs. There is a function called keybd_event which can toggle the capslock key

Private Declare Sub keybd_event Lib "user32" (ByVal key As Byte, ByVal bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As Long)

    Private Sub ToggleCapslock()
        keybd_event(Keys.Capital, 0, 0, 0)
        keybd_event(Keys.Capital, 0, &H2, 0)
    End Sub

In the above example we have called the keybd_event function twice. First for Keydown and second time for KeyUp (&H2 is value for KeyUp). If we want the code to work only to set capslock Off then we can change the code as below

   Private Sub SetCapslockOff()
If My.Computer.Keyboard.CapsLock = True Then
keybd_event(Keys.Capital, 0, 0, 0)
keybd_event(Keys.Capital, 0, &H2, 0)
Else
'Already off
End If
End Sub

No comments:

Post a Comment