C#WPF密钥持有

我有一个关键的问题。 当它只是关键时,一切都有效,但关键持有怎么办? 代码如下所示:

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

谢谢你的回复。

WPF KeyEventArgs类具有IsRepeat属性 ,如果按住该键,该属性将为true。

文章的例子:

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

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

首先是不断检查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(); }