C# WPF key held

2020-04-12 01:53发布

问题:

I have a problem with key held. Everything works when it's just key down but what about key holding? The code looks like this:

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

Thanks for replies.

回答1:

The WPF KeyEventArgs class has an IsRepeat property which will be true if the key is being held down.

Example from the article:

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


回答2:

I can see two ways to do this.

The first is to continually check the Keyboard.IsKeyDown for your keys.

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

The second is to simply kick off your moveBall method on the KeyDown event and continue doing it until you handle a corresponding KeyUp event.

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


标签: c# wpf key