0

I'm trying to register multiple keys with a WPF PreviewKeyDown event. Window_KeyDown(object sender, KeyEventArgs e)

If I press W I register W. if I then press E at the same time I register W and E. So fare so good.

But if I release one of the keys the event doesn't refire. However I want to keep register the KeyDown event to be able to register the other key which is still being pressed.

I have tried to keep it in a while loop and check for all keys being released before ending the while loop, but that is not a solution as it blocks the function.

public void Window_PreviewKeyDown(object sender, KeyEventArgs e)
{
    for (int i = 0; i < 255; i++)
    {
        int state = GetAsyncKeyState(i);
        if (state != 0)
        {
            if (i == 87)   // W
            {
               // collect the key press
            }
            if (i == 69)   //E
            {
               // collect the key press 
            }
        }
    }
}
paulsm4
  • 114,292
  • 17
  • 138
  • 190
Klask
  • 19
  • 2
  • 1
    You can't use a while-loop, events are only fired when Application.Run() is in control. Use a variable to keep track of key state or use Keyboard.IsKeyDown() – Hans Passant Sep 26 '22 at 12:26

1 Answers1

0

The PreviewKeyDown event will fire for each and every key press. Can you use IsKeyDown state for the specific key combination?

If(Keyboard.IsKeyDown(Key.A))
Hasse
  • 227
  • 3
  • 7
  • No, i can't use that. PreviewKeyDown fires when i press W, and then again when i press E. PreviewKeyDown keeps firing if I hold the keys down. but when i release one of the keys it stops firing. I need the event to keep firing until all keys are released. – Klask Sep 27 '22 at 04:58