C# WPF 按键保持

4

我遇到了按键按住的问题。当只是按下按键时,一切都正常,但是按键按住时怎么办?代码看起来像这样:

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);
    }
}

感谢回复。
2个回答

11

WPF 的 KeyEventArgs 类 有一个 IsRepeat 属性,如果按键被按住,则该属性值为 true。

本文示例:

// e is an instance of KeyEventArgs.
// btnIsRepeat is a Button.
if (e.IsRepeat)
{
    btnIsRepeat.Background = Brushes.AliceBlue;
}

干得好。看起来很不错,而且运行良好。非常感谢。 - Paweł Zarzecki

4
我可以看到两种方法来完成这个任务。
第一种是不断检查Keyboard.IsKeyDown是否按下了你的按键。
while (Keyboard.IsKeyDown(Key.Left) || Keyboard.IsKeyDown(Key.Right) || ...)
{
    moveBall(3);
}

第二种方法是在按键按下事件(KeyDown event)中启动您的moveBall方法,并继续执行,直到您处理相应的KeyUp事件。
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();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接