Get all keys that are pressed

Deukalion picture Deukalion · May 7, 2012 · Viewed 15k times · Source

What do I have to use to be able to get "all keys" that are pressed on the keyboard at the moment? Since Form.KeyPress += new EventHandler() doesn't do much at all when it's filled of controls. It doesn't call it no matter what I do, neither KeyDown, KeyUp or anything else... and yeah, I know how to use them.

So, if there's any function in the system that can check for pressed keys, that returns an array of the keys used or something - I would be grateful to be pointed in the right direction.

Answer

JaredPar picture JaredPar · May 7, 2012

It sounds like you want to query the state of all keys in the keyboard. The best function for that is the Win32 API call GetKeyboardState

I don't believe there is a good managed equivalent of that function. The PInvoke code for it is fairly straight forward

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetKeyboardState(byte [] lpKeyState);

var array = new byte[256];
GetKeyboardState(array);

This will populate the byte[] with the up / down state of every virtual key in the system. If the high bit is set then the virtual key is currently pressed. Mapping a Key to a virtual key code is done by only considering the byte portion of the numeric Key value.

public static byte GetVirtualKeyCode(Key key) {
  int value = (int)key;
  return (byte)(value & 0xFF);
}

The above works for most of the Key values but you need to be careful with modifier keys. The values Keys.Alt, Keys.Control and Keys.Shift won't work here because they're technically modifiers and not key values. To use modifiers you need to use the actual associated key values Keys.ControlKey, Keys.LShiftKey, etc ... (really anything that ends with Key)

So checking if a particular key is set can be done as follows

var code = GetVirtualKeyCode(Key.A);
if ((array[code] & 0x80) != 0) {
  // It's pressed
} else { 
  // It's not pressed
}