让我解释一下,在窗体上我有四个按钮和其他各种控件,如果用户按下其中一个按钮(触发游戏事件),那么该按钮就会获得焦点,我就无法使用箭头键捕获移动。
我尝试了以下代码:
private void KeyDown(KeyEventArgs e)
{
if (e.KeyCode == Keys.Left)
{
game.MovePlayer(DonutWarsLibrary.GameObjects.Direction.E);
game.DrawObjects(panel1.CreateGraphics());
}
else if (e.KeyCode == Keys.Right)
{
game.MovePlayer(DonutWarsLibrary.GameObjects.Direction.W);
game.DrawObjects(panel1.CreateGraphics());
}
else if (e.KeyCode == Keys.Up)
{
game.MovePlayer(DonutWarsLibrary.GameObjects.Direction.N);
game.DrawObjects(panel1.CreateGraphics());
}
else if (e.KeyCode == Keys.Down)
{
game.MovePlayer(DonutWarsLibrary.GameObjects.Direction.S);
game.DrawObjects(panel1.CreateGraphics());
}
}
然后当表单按键事件被按下时,我使用了这个
private void MainForm_KeyDown(object sender, KeyEventArgs e)
{
KeyDown(e);
}
我还为窗体上的按钮和其他控件添加了keydown,但是没有得到任何响应。我已经在函数内设置了断点以查看它是否被调用了,但是该断点从未触发?
有什么想法吗?
最优化的方法是具有通用的KeyDown事件触发器(无论当前拥有焦点的控件是什么),然后调用KeyDown方法。