简体   繁体   中英

C# WPF key held

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM