Programmically Toggling Capslock button


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


Comments

Author: Reets07 Feb 2010 Member Level: Gold   Points : 1

Hi Gaurav,

The posting is real worth and very helpful,

Thanks for help
Regards
Reet

Author: PHANI HARSHITHA MADALA09 Feb 2010 Member Level: Gold   Points : 1

Hi Mr.gaurav,

Very usefull info..

Thanks for sharing with all of us.


regards,

harshitha



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: