[英]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'.
但是,我在键盘上按了'a',但它出现'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.
问题是XNA不适合从键盘获取文本输入。 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). 虽然您可以编写自定义代码来检查是否按下shift等等,但是键盘不是您正在使用的键盘(例如,不同的语言,不同的布局)。 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/ 请参阅Promit的帖子: 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.Initialize in your game's
Initialize`方法中调用EventInput.Initialize in your game's
并订阅他的事件:
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! 注意:如果您允许输入任何字符(例如带有变音符号的外国字符等),请确保您的
SpriteFont
支持它们! (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). (如果没有,也许只是在将字体添加到文本字符串之前检查您的字体是否支持它,或者让spritefont使用特殊的“无效”字符)。
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
}
}
[...]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.