C# trying to capture the KeyDown event on a form

后端 未结 4 1032
不知归路
不知归路 2020-12-03 07:25

I am creating a small game, the game is printed onto a panel on a windows form. Now i want to capture the keydown event to see if its the arrow keys that has been pressed, t

4条回答
  •  再見小時候
    2020-12-03 07:58

    I believe the easiest way of solving this problem is through overriding the ProcessCmdKey() method of the form. That way, your key handling logic gets executed no matter what control has focus at the time of keypress. Beside that, you even get to choose whether the focused control gets the key after you processed it (return false) or not (return true).
    Your little game example could be rewritten like this:

    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        if (keyData == Keys.Left)
        {
            MoveLeft(); DrawGame(); DoWhatever();
            return true; //for the active control to see the keypress, return false
        }
        else if (keyData == Keys.Right)
        {
            MoveRight(); DrawGame(); DoWhatever();
            return true; //for the active control to see the keypress, return false
        }
        else if (keyData == Keys.Up)
        {
            MoveUp(); DrawGame(); DoWhatever();
            return true; //for the active control to see the keypress, return false
        }
        else if (keyData == Keys.Down)
        {
            MoveDown(); DrawGame(); DoWhatever();
            return true; //for the active control to see the keypress, return false
        }
        else
            return base.ProcessCmdKey(ref msg, keyData);
    }
    

提交回复
热议问题