在 WinForms 桌面应用程序中处理键盘上的箭头按钮触发的 KeyDown 和 KeyUp 事件
Handle KeyDown and KeyUp events triggering with arrow buttons on keyboard in WinForms desktop application
我想弄明白,如何处理 KeyDown
和 KeyUp
事件在 WinForms
C#
桌面应用程序中使用键盘上的箭头按钮触发,而不是使用button1
:
private void button1_Click(object sender, EventArgs e)
{
y = y - 10; // Go up
moveGraphicObject();
}
但是如果我使用箭头键,无论是否有其他表单控件都不会触发事件:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Left)
{
x = x - 10;
}
if (e.KeyCode == Keys.Right)
{
x = x + 10;
}
if (e.KeyCode == Keys.Up)
{
y = y - 10;
}
if (e.KeyCode == Keys.Down)
{
y = y + 10;
}
moveGraphicObject();
}
查看 PreviewKeyDown 事件。 MSDN 有一个很好的例子 here
By default, KeyDown does not fire for the ARROW keys PreviewKeyDown is
where you preview the key. Do not put any logic here, instead use the
KeyDown event after setting IsInputKey to true.
我想弄明白,如何处理 KeyDown
和 KeyUp
事件在 WinForms
C#
桌面应用程序中使用键盘上的箭头按钮触发,而不是使用button1
:
private void button1_Click(object sender, EventArgs e)
{
y = y - 10; // Go up
moveGraphicObject();
}
但是如果我使用箭头键,无论是否有其他表单控件都不会触发事件:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Left)
{
x = x - 10;
}
if (e.KeyCode == Keys.Right)
{
x = x + 10;
}
if (e.KeyCode == Keys.Up)
{
y = y - 10;
}
if (e.KeyCode == Keys.Down)
{
y = y + 10;
}
moveGraphicObject();
}
查看 PreviewKeyDown 事件。 MSDN 有一个很好的例子 here
By default, KeyDown does not fire for the ARROW keys PreviewKeyDown is where you preview the key. Do not put any logic here, instead use the KeyDown event after setting IsInputKey to true.