如何检测wpf中的多个按键按下onkeydown事件? [英] How to detect multiple keys down onkeydown event in wpf?
本文介绍了如何检测wpf中的多个按键按下onkeydown事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不想检测任何双键组合,所以像
I don't want to detect any double key combination, so solutions like
if(Keyboard.IsKeyDown(specificKey)){
}
不会工作,当然,除非我会检查每个关键状态,我希望我不必这样做..
won't work, unless of course, I will have check every single key state, which I'm hoping I won't have to do. .
private void TextBox_KeyDown_1(object sender, KeyEventArgs e)
{
Console.WriteLine(combination of keys pressed);
}
最终目标是检测任何(不是特定的组合/单键)组合键.
The end goal is to detect ANY (not a specific combination/single key) key combination.
LadderLogic 的解决方案完美运行.
LadderLogic's solution works perfectly.
推荐答案
重构你的代码:XAML:<TextBox Text="text" LostFocus="TextBox_LostFocus" KeyDown="TextBox_KeyDown" KeyUp="TextBox_KeyUp"/>
Refactored your code:
XAML:
<TextBox Text="text" LostFocus="TextBox_LostFocus" KeyDown="TextBox_KeyDown" KeyUp="TextBox_KeyUp"/>
代码隐藏:
List<Key> _pressedKeys = new List<Key>();
private void TextBox_KeyDown(object sender, KeyEventArgs e)
{
if (_pressedKeys.Contains(e.Key))
return;
_pressedKeys.Add(e.Key);
PrintKeys();
e.Handled = true;
}
private void TextBox_KeyUp(object sender, KeyEventArgs e)
{
_pressedKeys.Remove(e.Key);
PrintKeys();
e.Handled = true;
}
private void PrintKeys()
{
StringBuilder b = new StringBuilder();
b.Append("Combination: ");
foreach (Key key in _pressedKeys)
{
b.Append(key.ToString());
b.Append("+");
}
b.Length--;
Console.WriteLine(b.ToString());
}
private void TextBox_LostFocus(object sender, RoutedEventArgs e)
{
_pressedKeys.Clear();
}
这篇关于如何检测wpf中的多个按键按下onkeydown事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文