简体   繁体   中英

C# KeyDown not working

I have a picturebox that I want to relocate when a key is pressed. I'm making a game of pong. With the code below I want to make the paddle of player 1, which is a picturebox that should move up and down while a key is pressed. The following code doesn't seem to work:

public partial class Form1 : Form
{
    bool upPressed, downPressed;

    public Form1()
    {
        InitializeComponent();
    }

    private void PongTimer_Tick(object sender, EventArgs e)
    {
        if(upPressed){
            paddlePlayer1.Location = new Point(paddlePlayer1.Location.X, paddlePlayer1.Location.Y + 5);
        }
        if (downPressed)
        {
            MessageBox.Show("Numlock");
        }
    }

    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        if(e.KeyCode == Keys.Up){ 
            upPressed = true; 
        }
        if (e.KeyCode == Keys.NumLock)
        {
            downPressed = true;
        }
    }

    private void Form1_KeyUp(object sender, KeyEventArgs e)
    {
        if(e.KeyCode == Keys.Up){ 
            upPressed = false;
        }
    }
}

I used the Numlock to see if the problem was in the picture, this isn't the case. I've put the KeyPreview propery to true but this didnt solve it either. The timer does work properly.

I hope somebody here can tell me what I'm doing wrong.

This is a code example to move a PictureBox:

  1. Drag/drop a PictureBox on a form (in this case Form1).
  2. Change the Background color of the PictureBox to eg red. (This way it is visible during runtime).
  3. Implement the KeyDown event of Form1 (in this case Form1_KeyDown).
  4. Run the application.
  5. Start pressing an arrow key and the PictureBox will move.

    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        int x = pictureBox1.Location.X;
        int y = pictureBox1.Location.Y;

        if (e.KeyCode == Keys.Right) { x += 1; }
        else if (e.KeyCode == Keys.Left) { x -= 1; }
        else if (e.KeyCode == Keys.Up) { y -= 1; }
        else if (e.KeyCode == Keys.Down) { y += 1; }

        pictureBox1.Location = new Point(x, y);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM