[英]Handling more than one keypress and detecting keyup event
I am making a simple game and I use the following code to detect cursor keys: 我正在制作一个简单的游戏,我使用以下代码来检测光标键:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (Connection == null || Connection.IsOpen == false)
return true;
Thread.Sleep(SleepTime);
switch (keyData)
{
case Keys.Up:
GoForward();
return true;
case Keys.Right:
GoRight();
return true;
case Keys.Left:
GoLeft();
return true;
case Keys.Down:
GoBackward();
return true;
case Keys.Space:
Beep();
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
I also use this code to figure out if the user has released perviously presed key: 我还使用此代码来确定用户是否已发布以前预设的密钥:
private void MainForm_KeyUp(object sender, KeyEventArgs e)
{
StopRoomba();
}
I have 2 problems now: I want to add situation where user can press for example UP and RIGHT cursors simultaneously so the character goes up-right. 我现在有两个问题:我想添加一个用户可以同时按下UP和RIGHT游标的情况,这样角色就会向上移动。 How can I check for this condition in my code? 如何在我的代码中检查这种情况?
Also something strange happens (Or maybe its a default system). 还有一些奇怪的事情发生(或者它可能是一个默认系统)。 I can press 3 cursor keys at once or for example I hold UP key and then hold RIGHT key while still holding up and also holding DOWN while holding UP and RIGHT, my code reacts to all three codes. 我可以一次按下3个光标键,或者例如我按住向上键,然后按住向右键,同时仍然按住并按住向下按住向上和向右键,我的代码对所有三个代码作出反应。 In the picture below you can see the red directions have been pressed and get detected by my code (red = pressed): 在下面的图片中,您可以看到红色方向已被按下并被我的代码检测到(红色=按下):
My second problem is that the MainForm_KeyUp
sometimes does not detect key release and the character keeps going to the direction. 我的第二个问题是MainForm_KeyUp
有时不检测键释放,并且角色继续朝着方向前进。
Any tips/helps will be appriciated 任何提示/帮助都会受到关注
Keys is a flagged enumeration. Keys是一个标记的枚举。 Which means you can use bitwise comparisons to see if more than one key is pressed simultaneously. 这意味着您可以使用按位比较来查看是否同时按下了多个键。
case Keys.Up & Keys.Right:
...
break;
You can also check for individual keys using checks like the following: 您还可以使用以下检查检查各个键:
if ((keyData & Keys.Up) == Keys.Up)
GoForward();
if ((keyData & Keys.Right) == Keys.Right)
GoRight();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.