Luke Girvin
Luke Girvin

Reputation: 13422

How do I get the current state of Caps Lock in VB.NET?

How do I find out whether or not Caps Lock is activated, using VB.NET?

This is a follow-up to my earlier question.

Upvotes: 11

Views: 17378

Answers (4)

JumboUser155
JumboUser155

Reputation: 33

Create a Timer that is set to 5 milliseconds and is enabled.
Then make a label named label1. After, try the following code (in the timer event handler).

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    If My.Computer.Keyboard.CapsLock = True Then
        Label1.Text = "Caps Lock Enabled"
    Else
        Label1.Text = "Caps Lock Disabled"
    End If
End Sub

Upvotes: 2

Thomas Bailey
Thomas Bailey

Reputation: 301

The solution posted by .rp works, but conflicts with the Me.KeyDown event handler.
I have a sub that calls a sign in function when enter is pressed (shown below).
The My.Computer.Keyboard.CapsLock state works and does not conflict with Me.Keydown.

Private Sub WindowLogin_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown

    If Keyboard.IsKeyDown(Key.Enter) Then
        Call SignIn()
    End If

End Sub

Upvotes: 0

rp.
rp.

Reputation: 17673

Control.IsKeyLocked(Keys) Method - MSDN

Imports System
Imports System.Windows.Forms
Imports Microsoft.VisualBasic

Public Class CapsLockIndicator

    Public Shared Sub Main()
        if Control.IsKeyLocked(Keys.CapsLock) Then
            MessageBox.Show("The Caps Lock key is ON.")
        Else
            MessageBox.Show("The Caps Lock key is OFF.")
        End If
    End Sub 'Main
End Class 'CapsLockIndicator

C# version:

using System;
using System.Windows.Forms;

public class CapsLockIndicator
{
    public static void Main()
    {
        if (Control.IsKeyLocked(Keys.CapsLock)) {
            MessageBox.Show("The Caps Lock key is ON.");
        }
        else {
            MessageBox.Show("The Caps Lock key is OFF.");
        }
    }
}

Upvotes: 17

aku
aku

Reputation: 123966

I'm not an expert in VB.NET so only PInvoke comes to my mind:

Declare Function GetKeyState Lib "user32" 
   Alias "GetKeyState" (ByValnVirtKey As Int32) As Int16

Private Const VK_CAPSLOCK = &H14

If GetKeyState(VK_CAPSLOCK) = 1 Then ...

Upvotes: 2

Related Questions