Detect if any key is pressed in C# (not A, B, but any) Detect if any key is pressed in C# (not A, B, but any) wpf wpf

Detect if any key is pressed in C# (not A, B, but any)


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


Using the XNA framework you can use thw follow for checking if any key has been pressed.

Keyboard.GetState().GetPressedKeys().Length > 0


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.