Handling more than one keypress and detecting keyup event

时光毁灭记忆、已成空白 提交于 2019-12-08 05:02:37

问题


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. 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. 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.

Any tips/helps will be appriciated


回答1:


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


来源:https://stackoverflow.com/questions/13964265/handling-more-than-one-keypress-and-detecting-keyup-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!