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.
You should use key modifier in combination with your customized key
if ((Keyboard.Modifiers & ModifierKeys.Alt) == ModifierKeys.Alt) // Is Alt key pressed
{
if (Keyboard.IsKeyDown(Key.S) && Keyboard.IsKeyDown(Key.C))
{
// do something here
}
}
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With