39

如何在 .NET 中找到 NumLock、CapsLock 和 ScrollLock 键的状态?

4

4 回答 4

55

导入 WinAPI 函数GetKeyState

[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true, CallingConvention = CallingConvention.Winapi)]
public static extern short GetKeyState(int keyCode);

然后你可以像这样使用它:

bool CapsLock = (((ushort)GetKeyState(0x14)) & 0xffff) != 0;
bool NumLock = (((ushort)GetKeyState(0x90)) & 0xffff) != 0;
bool ScrollLock = (((ushort)GetKeyState(0x91)) & 0xffff) != 0;

它适用于框架 1.1。对于框架 2.0(及更高版本),您可以使用:

Control.IsKeyLocked

于 2009-02-23T12:02:51.323 回答
42

使用 Framework 2.0 及更高版本,您可以使用框架功能:

Control.IsKeyLocked(Keys) 方法

public static bool NumlockActive()
{
    return Control.IsKeyLocked(Keys.NumLock);
}
于 2011-05-26T07:37:42.213 回答
22

如果有人在 WPF 中开发时遇到此线程,您可以使用 .NET 3.0 中引入的Keyboard.IsToggled方法:

var isNumLockToggled = Keyboard.IsKeyToggled(Key.NumLock);
var isCapsLockToggled = Keyboard.IsKeyToggled(Key.CapsLock);
var isScrollLockToggled = Keyboard.IsKeyToggled(Key.Scroll);

如果还没有,您必须将以下using指令添加到您的类的顶部:

using System.Windows.Input;

Internally, the IsToggled() method checks to see whether or not the KeyStates.Toggled flag is set for the specified key.

[Flags]
public enum KeyStates : byte
{
    None = (byte) 0,
    Down = (byte) 1,
    Toggled = (byte) 2,
}
于 2015-04-21T15:35:49.030 回答
8

Check State

To check state of CapsLock, NumLock and ScrollLock keys you can use Control.IsKeyLocked method:

var capsLockIsOn = Control.IsKeyLocked(Keys.CapsLock);

Actively Show The State in UI in status bar

Since the lock keys can be turn on or turn off when your application doesn't have focus handling keyboard events of the form is not enough to detect changes on the key lock state and you should also put your logic in some other places like activation event of your form or you need to register a global keyboard hook.

As a simple and reliable solution you can check their status in Application.Idle event. You must detach your idle event handler when your form closed.

public Form1()
{
    InitializeComponent();
    Application.Idle += Application_Idle;
}

void Application_Idle(object sender, EventArgs e)
{
    if (Control.IsKeyLocked(Keys.CapsLock))
        toolStripStatusLabel1.Text = "CapsLock is On";
    else
        toolStripStatusLabel1.Text = "";
}

protected override void OnFormClosed(FormClosedEventArgs e)
{
    Application.Idle -= Application_Idle;
    base.OnFormClosed(e);
}
于 2016-04-08T10:16:31.347 回答