将箭头键焦点更改为移动播放器而不是按钮

Changing the arrow-keys focus to moving the player instead of buttons

所以我正在使用 c# 中的表单(类似于贪吃蛇游戏)构建游戏,并且我想使用箭头键在播放器中导航。在玩游戏的网格(板)附近,我有几个按钮,例如;暂停,开始等。当我单击箭头键时,焦点在按钮上(它正在浏览按钮)而不是移动播放器。我该如何更改?

问候,

亨克

首先,您必须在设计器中将表单 KeyPreview 设置为 true 并订阅表单的 KeyDownevent 或将此行添加到表单的构造函数中:

this.KeyPreview = true;
this.KeyDown += Form1_KeyDown;

然后,为按键事件添加这段代码。基本上,如果按下的键是箭头之一,它会告诉事件已经处理了按键:

private void Form3_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode==Keys.Up || e.KeyCode == Keys.Down || e.KeyCode == Keys.Left ||e.KeyCode == Keys.Right)
    {
        e.Handled = true;
        MovePlayer(e.KeyCode);
    }
}

private void MovePlayer(Keys key)
{
    switch (key)
    {
        case Keys.Up:
            // your player moveup code
            break;
        ...
    }
}