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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/58976/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 11:11:02  来源:igfitidea点击:

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

.netwindowsvb.net

提问by Luke Girvin

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

如何使用 VB.NET 确定 Caps Lock 是否已激活?

This is a follow-up to my earlier question.

这是我之前问题的后续。

回答by rp.

Control.IsKeyLocked(Keys) Method - MSDN

Control.IsKeyLocked(Keys) 方法 - 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:

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

回答by aku

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

我不是 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 ...

回答by JumboUser155

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).

创建一个设置为 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

回答by Thomas Bailey

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

.rp发布的解决方案有效,但与Me.KeyDown事件处理程序冲突。
我有一个 sub 在按下 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