-2

I trying to develop a program using vb .net that could check or uncheck a check box when the caps lock key is pressed. I used the below code to do the same, but its not working.

Private Sub Form1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress
    If e.KeyChar = Microsoft.VisualBasic.ChrW(Keys.CapsLock) Then
        checkbutton_caps.Checked = True
    End If

So what's wrong with the above code?

Xlam
  • 133
  • 2
  • 11
  • Try changing `Microsoft.VisualBasic.ChrW(Keys.CapsLock)` to `Control.IsKeyLocked(Keys.CapsLock)` – MusicLovingIndianGirl Jun 24 '16 at 09:47
  • 1
    Try `If My.Computer.Keyboard.CapsLock = True Then`. – Visual Vincent Jun 24 '16 at 09:47
  • You're handling the wrong event. `KeyPress` is raised in response to key combinations (where a combination may be just one key) that result in a character being produced for input. The CapsLock key does not produce a character. You'd have to handle `KeyDown` or `KeyUp`, which are raised in response to single keyboard keys. That said, certain keys don't produce those events either by default. Not sure whether CapsLock does or not. – jmcilhinney Jun 24 '16 at 09:50

3 Answers3

2

Both these code will work.

➤ Setting KeyPreview = True

Private Sub Form1_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown
    If e.KeyCode = Keys.CapsLock Then
        checkbutton_caps.Checked = True            
    End If
End Sub

➤ Without using the KeyPreview Property (Simply, add this code to your program).

Protected Overrides Function ProcessCmdKey(ByRef Msg As Message, _
                                           ByVal Key As Keys) _
                                           As Boolean
    If Msg.WParam = Keys.CapsLock Then
       checkbutton_caps.Checked = True           
       Return True
    End If
       Return Me.ProcessCmdKey(Msg, Key)
End Function

Tip: Use this code to uncheck the checkbox when the key is pressed again.

checkbutton_caps.Checked = Not checkbutton_caps.Checked

'Instead of...

checkbutton_caps.Checked = True 
Raktim Biswas
  • 4,011
  • 5
  • 27
  • 32
0
Imports System
Imports System.Windows.Forms
Imports Microsoft.VisualBasic

Public Function GetCapsLockState() As Boolean
    If Control.IsKeyLocked(Keys.CapsLock) Then
        Return True
    Else
        Return False
    End If
End Function

If GetCapsLockState Then
    checkbutton_caps.Checked = True
End If
BanForFun
  • 752
  • 4
  • 15
0
Private Sub Form1_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown
    If e.KeyCode = Keys.Capital Then
        CheckBox1.Checked = Not CheckBox1.Checked
    End If
End Sub

Both Capital and CapsLock will work.

Also remember to set Me.KeyPreview = True either in code or properties.

This is useful study about keydown vs keypress

Community
  • 1
  • 1
Claudius
  • 1,883
  • 2
  • 21
  • 34