I’m working with some code that simulates a key press. Everything is working fine, I can see keys being pressed as expected (testing with Capslock/Numlock at the moment, so I can see LEDs on the keyboard). However, for my needs I need to be able to tell 100%, whether or not were these keys pressed. My app acts weird, so I’ve decided to reproduce the problem in a smaller scale and I’ve found a very odd thing. Function IsKeyLocked doesn’t return a result I’d expect.
Let’s have a code like this:
private void btnPressButton_Click(object sender, EventArgs e)
{
KeyboardManager.PressKey(KeyCode.CapsLock);
lblKeyboardState.Text = IsKeyLocked(Keys.CapsLock).ToString();
}
Method for pressing the keys:
[DllImport("user32.dll", SetLastError = true)]
private static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);
public static void PressKey(KeyCode keyCode)
{
byte code = (byte)keyCode;
keybd_event(code, 0, KEYEVENTF_KEYDOWN, 0);
keybd_event(code, 0, KEYEVENTF_KEYUP, 0);
}
One would expect, that after the first button click, the result will be True (Capslock wasn’t pressed when I run the app). But it’s False, even though the LED on my keyboard is shining. When I press the button again, result is True, but the LED isn’t shining anymore. WHY is this function returning a wrong result? Am I missing something or…?
According to msdn documentation:
Determines whether the CAPS LOCK, NUM LOCK, or SCROLL LOCK key is in
effect.
If this is a true statement, what actually happens here? How to get 100% reliable answer from C#, whether or not is capslock/numlock in effect?
I believe the reason you’re seeing this behavior is because your code sets the state of the CapsLock then checks the state before the event of the Caps key locking happens in the application. You can make your sample code function correctly by simply adding a DoEvents() statement in your code between setting the CapsLock state, and checking it.