处理多个按键并检测按键事件 [英] Handling more than one keypress and detecting keyup event

查看:263
本文介绍了处理多个按键并检测按键事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个简单的游戏,并且使用以下代码来检测光标键:

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();
}

我现在有2个问题:我想添加一种情况,用户可以同时按下例如UP和RIGHT光标,从而使角色向右移动.如何在我的代码中检查这种情况?

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. How can I check for this condition in my code?

还发生了一些奇怪的事情(或者可能是默认系统).我可以一次按下3个光标键,例如我按住UP键,然后按住RIGHT键的同时仍然按住,同时按住DOWN键的同时按住UP和RIGHT键,我的代码对所有三个代码做出反应.在下面的图片中,您可以看到红色方向已被按下并被我的代码检测到(红色=已按下):

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. In the picture below you can see the red directions have been pressed and get detected by my code (red = pressed):

我的第二个问题是MainForm_KeyUp 有时有时无法检测到按键的释放,并且角色一直朝着该方向前进.

My second problem is that the MainForm_KeyUp sometimes does not detect key release and the character keeps going to the direction.

任何提示/帮助都会被应用

Any tips/helps will be appriciated

推荐答案

键是已标记的枚举.这意味着您可以使用按位比较来查看是否同时按下了多个键.

Keys is a flagged enumeration. 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();

这篇关于处理多个按键并检测按键事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆