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