【问题标题】:C# WPF key held持有 C# WPF 密钥
【发布时间】:2013-12-28 19:40:24
【问题描述】:

我的钥匙有问题。当它只是按下键时一切正常,但是键保持呢?代码如下所示:

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

感谢您的回复。

【问题讨论】:

    标签: c# wpf key


    【解决方案1】:

    WPF KeyEventArgs 类 has an IsRepeat property 如果按键被按住则为真。

    文章示例:

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

    【讨论】:

    • 干得好。它看起来不错并且工作正常。非常感谢。
    【解决方案2】:

    我可以看到两种方法来做到这一点。

    首先是不断检查 Keyboard.IsKeyDown 是否有您的键。

    while (Keyboard.IsKeyDown(Key.Left) || Keyboard.IsKeyDown(Key.Right) || ...)
    {
        moveBall(3);
    }
    

    第二种方法是简单地在 KeyDown 事件上启动 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();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-18
      • 1970-01-01
      • 1970-01-01
      • 2011-05-22
      • 2017-07-21
      • 1970-01-01
      • 2022-12-09
      相关资源
      最近更新 更多