[EDIT 3] I kind of "solved it" by at using the "strange" version. At least for the most important keys. It is suffient for my case, where I want to check
http://sourceforge.net/projects/keystate/ shows "special" keys. Otherwise I think you're just going to have to monitor them. SOunds like you want to do this systemwide? What are you trying to accomplish?
[DllImport("user32.dll", EntryPoint = "GetKeyboardState", SetLastError = true)]
private static extern bool NativeGetKeyboardState([Out] byte[] keyStates);
private static bool GetKeyboardState(byte[] keyStates)
{
if (keyStates == null)
throw new ArgumentNullException("keyState");
if (keyStates.Length != 256)
throw new ArgumentException("The buffer must be 256 bytes long.", "keyState");
return NativeGetKeyboardState(keyStates);
}
private static byte[] GetKeyboardState()
{
byte[] keyStates = new byte[256];
if (!GetKeyboardState(keyStates))
throw new Win32Exception(Marshal.GetLastWin32Error());
return keyStates;
}
private static bool AnyKeyPressed()
{
byte[] keyState = GetKeyboardState();
// skip the mouse buttons
return keyState.Skip(8).Any(state => (state & 0x80) != 0);
}
In the Key Enumeration there is an Enumeration value of Zero(0), which basically tests "No Key Pressed", which is opposite of "Any key pressed". So, something like this might work;
If !GetKeyState(0)==True then
Do Something
End If
Or
If GetKeyState(0)==False then
Do Something
End If
You can increment a counter for each keydown event, and decrement it for each keyup event. When the counter is zero, no keys are down.
Quite an old question but in case anyone comes across this and doesn't want to use external dll's, you could just enumerate the possible keys and loop over them.
bool IsAnyKeyPressed()
{
var allPossibleKeys = Enum.GetValues(typeof(Key));
bool results = false;
foreach (var currentKey in allPossibleKeys)
{
Key key = (Key)currentKey;
if (key != Key.None)
if (Keyboard.IsKeyDown((Key)currentKey)) { results = true; break; }
}
return results;
}
You could optimize this a bit by doing the enum outside of the function and retaining the list for later.
If you're using Windows.Forms
, use the KeyDown
event and read out the specific key using the appropriate KeyEventArgs
. You can access the KeyCode
property on the KeyEventArgs
variable.
To check for ranges, say between A and Z:
if (e.KeyCode>=Keys.A && e.KeyCode<=Keys.Z)
{
// do stuff...or not
}