[英]C# If more keys are pressed at once how to not stop functions of others?
I know the title was little unclear but i will explain. 我知道标题不太清楚,但我会解释。 My Example: when i press 'D' my object will move to right, same for 'A' just move to left, but when i press 'Space' while holding 'A'/'D',the object will just o the function of the 'Space'.
我的示例:当我按'D'时,对象将向右移动,与'A'相同,只是向左移动,但是当我在按住'A'/'D'的同时按'Space'时,对象将随函数“太空”。
if (e.KeyCode == Keys.A)
{
ply.Left -= 3;
}
if (e.KeyCode == Keys.D)
{
ply.Left += 3;
}
if (e.KeyCode == Keys.Space) {
ply.Top -= 100;
}
You can track the state of multiple keys through the use of both KeyUp
and KeyDown
by use of a HashSet<Keys>
: 您可以通过使用
HashSet<Keys>
来同时使用KeyUp
和KeyDown
来跟踪多个键的状态:
private HashSet<Keys> _keys = new HashSet<Keys>();
public void Control_KeyDown(object sender, KeyEventArgs e)
{
_keys.Add(e.KeyCode);
}
public void Control_KeyUp(object sender, KeyEventArgs e)
{
_keys.Remove(e.KeyCode);
}
public bool IsKeyDown(Keys keyCode)
{
return _keys.Contains(keyCode);
}
Now, whenever you want to check to see if a key is down, just do: 现在,每当您要检查按键是否按下时,只需执行以下操作:
if(IsKeyDown(Keys.A))
{
ply.Left -= 3;
}
Keep in mind that if you just check key states in one of the key events, you will probably have issues with not detecting repeats properly. 请记住,如果仅检查关键事件之一中的关键状态,则可能会遇到无法正确检测重复的问题。 If you really want to handle this properly, you should use a
Timer
with a fairly small Interval
that periodically polls with IsKeyDown
and handles all your input. 如果您确实想正确处理此问题,则应使用一个具有较小
Interval
的Timer
,该Timer
会定期通过IsKeyDown
轮询并处理所有输入。
With a Timer
named timer1
that has an interval of 100
, you can handle all your input like this, and have fairly responsive input to the full range of keys supported by your hardware. 使用间隔时间为
100
名为timer1
的Timer
,您可以像这样处理所有输入,并且对硬件支持的所有键范围具有相当敏感的输入。
private void timer1_Tick(object sender, EventArgs e)
{
if (IsKeyDown(Keys.A))
{
ply.Left -= 3;
}
if (IsKeyDown(Keys.S))
{
ply.Top += 3;
}
if (IsKeyDown(Keys.D))
{
ply.Left += 3;
}
if (IsKeyDown(Keys.W))
{
ply.Top -= 3;
}
}
As Bradley said, you could save all key events to a keystate cache. 正如Bradley所说,您可以将所有键事件保存到键状态缓存中。
This could look something like this pseudo code: 这可能看起来像下面的伪代码:
Event KeyDown(e) -> keystate[e.KeyCode] = true
Event KeyUp(e) -> keystate[e.KeyCode] = false
That way, you should always know every state. 这样,您应该始终了解每个状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.