0

I'm very new to programming and I'm currently doing a Pong project and as I was trying the program out for the first time I noticed that if I press an Arrow Key the other keys would stop working. Why is that?

The KeyEventArgs

protected override void OnKeyDown(KeyEventArgs e)
{
    base.OnKeyDown(e);
    if (e.KeyCode == Keys.W) upKeyPressed = true;
    if (e.KeyCode == Keys.S) downKeyPressed = true;
    if (e.KeyCode == Keys.Escape) paused = !paused;
}

protected override void OnKeyUp(KeyEventArgs e)
{
    base.OnKeyUp(e);
    if (e.KeyCode == Keys.W) upKeyPressed = false;
    if (e.KeyCode == Keys.S) downKeyPressed = false;
}

so basically I'm using 'W' and 'S' to move my "paddles" but as soon as I press an arrow key the W and the S stops working...

The code I use to move my paddle with W and S:

private void moveBall(object sender, EventArgs e)
{
    //If not paused we can "start" the game
    if (!paused)
    {
        //Player 1
        if (upKeyPressed && Paddle1.Location.Y > topBounds)
        {
            Paddle1.Location = new Point(Paddle1.Location.X, Paddle1.Location.Y - 5);
        }
        else if (downKeyPressed && (Paddle1.Location.Y + Paddle1.Height) < bottomBounds)
        {
            Paddle1.Location = new Point(Paddle1.Location.X, Paddle1.Location.Y + 5);
        }
    }
}

And I have a timer with the interval of 1 for the code above And then it's just a paddle in a picturebox as the Image shows

I don't know how much you need to be able to see what the problem is but I can obviously take more pictures or upload the whole program.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Eekan
  • 11
  • 2
  • Welcome to StackOverflow. We invite you to take the [tour] and take some tips on [ask]. Don't post you code as picture, paste it as text (so we can copy and try it out). – Rodrigo Rodrigues May 24 '21 at 21:25

1 Answers1

0

As per this Stackoverflow post by Rodolfo Neuber.

I recently stumbled across this article from microsoft, which looks quite
promising: 
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.previewkeydown.aspx
According to microsoft, the best thing to do is set 
e.IsInputKey=true; in the PreviewKeyDown event after detecting 
the arrow keys. Doing so will fire the KeyDown event.

This worked quite well for me and was less hack-ish than overriding the ProcessCMDKey.

For context, this means you create another listner PreviewKeyDown, and in it set the parameter (KeyDownEvent) to have IsInputKey be true.

This then reads your arrow's onKeyDownEvent as the arrowkey being pressed into the program, rather than the OS.

As an example, think about how you can alt-tab in any window and it isn't read by the program, but instead by windows itself, changing active window.

Arrow keys obviously work the same way.

StarshipladDev
  • 1,166
  • 4
  • 17