C# Actively detect Lock keys

后端 未结 4 1228
我在风中等你
我在风中等你 2021-01-24 06:38

I have a wireless keyboard and mouse that doesn\'t have any lock indicators, nor any software bundled to provide a visual aid, so I\'m making my own.

I got it so that if

4条回答
  •  后悔当初
    2021-01-24 06:54

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

提交回复
热议问题