C# Actively detect Lock keys

后端 未结 4 1227
我在风中等你
我在风中等你 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:43

    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.

提交回复
热议问题