Kyle Neary
Kyle Neary

Reputation: 21

C# XNA 4.0 Check if Any Key is Pressed EXCEPT One

I'm trying to write a program in C# XNA and I need to have the program do something if any key except a certain one is pressed. Here's what I want to try to do:

if (keyboard.IsKeyPressed(Keys.A))
{
    do stuff;
}
else if (ANY OTHER KEY)
{
    do other stuff;
}

Upvotes: 2

Views: 1190

Answers (2)

user4516065
user4516065

Reputation:

Alexandru provided a correct answer, but I'll go through why it works. It's always useful to understand what you're doing.

Since Keyboard.GetState().GetPressedKeys() is an array, you can use the length (or count) to see if a key is pressed:

if (Keyboard.GetState().GetPressedKeys().Length > 0)
{
   // Do something.
}

And because all pressed keys are stored in this array, you can see what specific keys are in there. That's why you are able to check it with the Contains(Keys.YourSpecificKey)) method.

You can then use this to check if this particular key is not inside the array using ! in a boolean expression.

var keys = Keyboard.GetState().GetPressedKeys();
if (keys.Count() > 0 && !keys.Contains(Keys.A)) 
{
   // Do something.
}

Since this code is (probably) located in your Update(GameTime gameTime) method, it will be checked 60 times per second.

Upvotes: 2

Alexandru
Alexandru

Reputation: 12932

Use Keyboard.GetState().GetPressedKeys().

For example:

var keys = Keyboard.GetState().GetPressedKeys();
if (keys.Count() > 0 && !keys.Contains(Keys.A)) {
   // Do something.
}

P.S. The above code is not tested.

Upvotes: 2

Related Questions