如何检测多键按下的onkeydown在WPF的事件吗? [英] How to detect multiple keys down onkeydown event in wpf?
问题描述
我不希望检测到任何双的组合键,因此像
解决方案
如果(Keyboard.IsKeyDown(specificKey) ){
}
将不起作用,除非,当然,我将检查每一个关键的状态,我希望我不会做的。
私人无效TextBox_KeyDown_1(对象发件人,发送KeyEventArgs E)
{
控制台。的WriteLine(按键的组合);
}
编辑:
的最终目标是检测到任何(不是。特定的组合/单键)组合键
EDIT2:LadderLogic的解决方案完美的作品
重构代码:
XAML:
<文本框文本=文本引发LostFocus =TextBox_LostFocus的KeyDown =TextBox_KeyDown的KeyUp =TextBox_KeyUp/ >
后台代码:
列表与LT;关键> _pressedKeys =新的List<关键>();
私人无效TextBox_KeyDown(对象发件人,发送KeyEventArgs E)
{
如果(_pressedKeys.Contains(e.Key))
的回报;
_pressedKeys.Add(e.Key);
PrintKeys();
e.Handled = TRUE;
}
私人无效TextBox_KeyUp(对象发件人,发送KeyEventArgs E)
{
_pressedKeys.Remove(e.Key);
PrintKeys();
e.Handled = TRUE;
}
私人无效PrintKeys()
{
StringBuilder的B =新的StringBuilder();
在b.append(组合:);
的foreach(在_pressedKeys键键)
{
在b.append(key.ToString());
在b.append(+);
}
b.Length--;
Console.WriteLine(b.ToString());
}
私人无效TextBox_LostFocus(对象发件人,RoutedEventArgs E)
{
_pressedKeys.Clear();
}
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);
}
EDIT: The end goal is to detect ANY (not a specific combination/single key) key combination.
EDIT2: LadderLogic's solution works perfectly.
Refactored your code:
XAML:
<TextBox Text="text" LostFocus="TextBox_LostFocus" KeyDown="TextBox_KeyDown" KeyUp="TextBox_KeyUp"/>
code-behind:
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();
}
这篇关于如何检测多键按下的onkeydown在WPF的事件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!