简体   繁体   中英

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

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 (eg 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 (eg 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
  }
}
[...]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM