Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I detect lowercase keys using the Keys enum in C#?

Tags:

c#

key

xna

for (Keys k = Keys.A; k <= Keys.Z; k++)
{
    if (KeyPress(k))
        Text += k;
}

This code detects the key buttons I pressed in my keyboard and it will print out what key is pressed in the console. However, I pressed 'a' on the keyboard but it comes out as 'A'. How do I fix this?

like image 828
Zainu Avatar asked Dec 28 '22 11:12

Zainu


2 Answers

This is an often encountered problem. The trouble is that XNA isn't geared towards getting textual input from a keyboard. It's geared towards getting the current state of each key on the keyboard.

While you could write custom code to check things like whether shift is held down etc, what about keyboards that aren't the one you're using (e.g. different language, different layout). What most people do is get windows to do it for you.

If you want text to appear as expected you need to basically re-create a few things and get windows to do it for you.

See Promit's post here: http://www.gamedev.net/topic/457783-xna-getting-text-from-keyboard/

Usage:

Add his code to your solution. Call EventInput.Initialize in your game'sInitialize` method and subscribe to his event:

EventInput.CharEntered += HandleCharEntered;

public void HandleCharEntered(object sender, CharacterEventArgs e)
{
    var charEntered = e.Character;
    // Do something with charEntered
}

Note: If you allow any character to be inputted (e.g. foreign ones with umlauts etc.) make sure your SpriteFont supports them! (If not, maybe just check your font supports it before adding it to your text string or get the spritefont to use a special 'invalid' character).

like image 136
George Duckett Avatar answered Dec 30 '22 12:12

George Duckett


After looking at your provided code, it should be a simple modification:

[...]
for (Keys k = Keys.A; k <= Keys.Z; k++)
{
  if (KeyPress(k))
  {
      if (keyboardState.IsKeyDown(Keys.LeftShift) || keyboardState.IsKeyDown(Keys.RightShift)) //if shift is held down
          Text += k.ToString().ToUpper(); //convert the Key enum member to uppercase string
      else
          Text += k.ToString().ToLower(); //convert the Key enum member to lowercase string
  }
}
[...]
like image 38
A-Type Avatar answered Dec 30 '22 12:12

A-Type