我遇到了按键按住的问题。当只是按下按键时,一切都正常,但是按键按住时怎么办?代码看起来像这样:
private void Window_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Left || e.Key == Key.Right || e.Key == Key.Up || e.Key == Key.Down)
{
moveBall(3);
}
}
感谢回复。
WPF 的 KeyEventArgs 类 有一个 IsRepeat 属性,如果按键被按住,则该属性值为 true。
本文示例:
// e is an instance of KeyEventArgs.
// btnIsRepeat is a Button.
if (e.IsRepeat)
{
btnIsRepeat.Background = Brushes.AliceBlue;
}
while (Keyboard.IsKeyDown(Key.Left) || Keyboard.IsKeyDown(Key.Right) || ...)
{
moveBall(3);
}
private void Window_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Left || e.Key == Key.Right ...)
// think about running this on main thread
StartMove();
}
private void Window_KeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.Left || e.Key == Key.Right ...)
// think about running this on main thread
StopMove();
}