如何在VB.NET中获取Caps Lock的当前状态?

时间:2008-09-12 13:37:16

标签: .net windows vb.net

如何使用VB.NET查看Caps Lock是否已激活?

这是我earlier question的后续行动。

4 个答案:

答案 0 :(得分:14)

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#版本:

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.");
        }
    }
}

答案 1 :(得分:2)

我不是VB.NET的专家,所以我只想到PInvoke:

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

Private Const VK_CAPSLOCK = &H14

If GetKeyState(VK_CAPSLOCK) = 1 Then ...

答案 2 :(得分:1)

创建一个设置为5毫秒且已启用的计时器 然后制作一个名为label1的标签。之后,尝试以下代码(在计时器事件处理程序中)。

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

答案 3 :(得分:0)

.rp发布的解决方案有效,但与Me.KeyDown事件处理程序冲突 当按下enter键时,我有一个调用登录功能的子程序(如下所示) My.Computer.Keyboard.CapsLock状态有效且与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