Handling more than one keypress and detecting keyu

2019-04-15 02:26发布

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):

enter image description here

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条回答
欢心
2楼-- · 2019-04-15 02:51

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();
查看更多
登录 后发表回答