Search code examples
c#keyboardxnastate

Detecting multiple key presses in C# and XNA 4.0


I want to detect if a specific set of keyboard keys are being held down at once in C# and XNA 4.0. I'm doing so with the following code:

KeyboardState keyState = Keyboard.GetState();

if(keyState.IsKeyDown(Keys.S) && keyState.IsKeyDown(Keys.K) && keyState.IsKeyDown(Keys.I))
{
    //Do something
}

This code detects if the user is pressing "S", "K" and "I" all at once. However, I've noticed that this code worked fine on one computer (Windows 8.1 laptop), but not on another (Windows 8 desktop). Additionally, I originally wanted the if statement to check if the user was also holding down the P key ("S", "K", "I" and "P" all at once), but when adding the fourth condition (keyState.IsKeyDown(Keys.P)), the code didn't work on either computer. Why would this code not work on multiple machines? And why would it glitch up and not work at all when trying to detect more than three keys at once?


Solution

  • This is most likely a hardware problem - called keyboard ghosting -, not a software problem. For my experience, it most commonly happens with 3 keys down, and the 4th key breaks almost all conventional keyboards. The link is a detailed explanation of this problem, and a test to see if it's really keyboard ghosting you're experiencing.

    There's nothing you can do about it in your code since it's a hardware problem, except for redesigning it so it fits the hardware, i.e. not to require three key downs, or different keys...

    If you really want this code to work, buy a keyboard with 6-key rollover(6 keys maximum) or n-key rollover(all keys on keyboard). This feature means that the keyboard's keys can all be pressed at once simultaneously, while all keys are still detected by the computer.

    Oh, and here is an excellent video that explains this problem in a very simple way.