C# Actively detect Lock keys

你离开我真会死。 提交于 2019-12-02 06:28:03

You will want to register some sort of keyboard hook to listen for the key presses and then retrieve the state of the lock keys like this:
http://blogs.msdn.com/b/toub/archive/2006/05/03/589423.aspx

In addition to the above article, make the below modifications to capture state of the lock keys:

private static IntPtr HookCallback(
    int nCode, IntPtr wParam, IntPtr lParam)
{
    if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
    {
        int vkCode = Marshal.ReadInt32(lParam);
        Keys key = (Keys)vkCode;
        if (key == Keys.Capital)
        {
            Console.WriteLine("Caps Lock: " + !Control.IsKeyLocked(Keys.CapsLock)); 
        }
        if (key == Keys.NumLock)
        {
            Console.WriteLine("NumLock: " + !Control.IsKeyLocked(Keys.NumLock));
        }
        if (key == Keys.Scroll)
        {
            Console.WriteLine("Scroll Lock: " + !Control.IsKeyLocked(Keys.Scroll));
        }
        Console.WriteLine((Keys)vkCode);
    }
    return CallNextHookEx(_hookID, nCode, wParam, lParam);
}

Here is an example for intercepting the keyup on a form or something and tracking it. I changed a local variable, but you can just as easily trigger GUI updates at that time.

    private bool capLock;
    private bool numLock;
    private void Form1_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.CapsLock)
        {
            capLock = !capLock;
        }
        if (e.KeyCode == Keys.NumLock)
        {
            numLock = !numLock;
        }
    }

Look at the following article on global keyboard events. When one of the locks keys is pressed you could update your UI...

http://www.codeproject.com/Articles/7294/Processing-Global-Mouse-and-Keyboard-Hooks-in-C

You can use Control.IsKeyLocked(...) method as described here: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.iskeylocked%28v=vs.100%29.aspx.

The method is available since .NET 2.0 and can be used like this:

bool capsLock = Control.IsKeyLocked(Keys.CapsLock);
bool numLock = Control.IsKeyLocked(Keys.NumLock);
bool scrollLock = Control.IsKeyLocked(Keys.Scroll);

This solution doesn't require importing WinApi functions or manually tracking keys states.

Update

In order to track changes of the lock keys, I can suggest You to try one of those solutions:

  • Adding a global hook to catch all key presses and then check if the key pressed was one of the lock keys. This would, however, make Your hook run each time any key is pressed. You can find more information about global hooks for keyboard keys here: http://blogs.msdn.com/b/toub/archive/2006/05/03/589423.aspx.
  • You can also implement a timer executing once in a while, check the key states and inform the user, if state of any of them was changed. If You don't run the timer too often, it shouldn't take much resources.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!