Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect multiple keys down onkeydown event in wpf?

Tags:

c#

events

wpf

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.

like image 985
CoolCodeBro Avatar asked Sep 25 '13 19:09

CoolCodeBro


2 Answers

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
  }
 }
like image 69
BRAHIM Kamel Avatar answered Oct 21 '22 03:10

BRAHIM Kamel


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();
}
like image 5
LadderLogic Avatar answered Oct 21 '22 05:10

LadderLogic