0

Is there a way to track key press and release actions on WPF?

This is what I've tried so far, but what I'm finding is that the _upDownKeyIsPressed is only set to false if I press another key - not when the up or down key is released

    private void KeyUpPress(KeyEventArgs e)
    {
        if (e.Key == Key.Up || e.Key == Key.Down)
        {
            _upDownKeyIsPressed = true;
            Console.WriteLine(_upDownKeyIsPressed.ToString());
        }
    }

    private void KeyDownPress(KeyEventArgs e)
    {
        if (e.Key == Key.Up || e.Key == Key.Down)
        {
            _upDownKeyIsPressed = false;
            Console.WriteLine(_upDownKeyIsPressed.ToString());
        }
    }

    private void PlotListView_KeyUp(object sender, KeyEventArgs e)
    {
        KeyUpPress(e);
    }

    private void PlotListView_KeyDown(object sender, KeyEventArgs e)
    {
        KeyDownPress(e);
    }
methuselah
  • 12,766
  • 47
  • 165
  • 315

1 Answers1

1

If you want to try what I said in comment. I think about something like this :

    private void PlotListView_KeyUp(object sender, KeyEventArgs e)
    {
        TrackUpDownKeyPress(e, false);
    }

    private void PlotListView_KeyDown(object sender, KeyEventArgs e)
    {
        TrackUpDownKeyPress(e, true);
    }

    private void TrackUpDownKeyPress(KeyEventArgs e, bool isPressed)
    {
        if (e.Key == Key.Up || e.Key == Key.Down)
            _upDownKeyIsPressed = isPressed;
    }

If you want more info about the difference between keyUp and keyDown, check this question.

Community
  • 1
  • 1
aloisdg
  • 22,270
  • 6
  • 85
  • 105