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?
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's
Initialize` 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).
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
}
}
[...]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With