1

I'm working on making pong in C#, and I've come across a problem. I have KeyPreview on, and here's my code

private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == (char)Keys.Up || e.KeyChar == (char)Keys.W) {
        picPaddle.Top -= 10;
    }
    else if (e.KeyChar == (char)Keys.Down || e.KeyChar == (char)Keys.S) {
        picPaddle.Top += 10;
    }
}

When I press any of the keys, nothing happens. The only time a keypress works is if it tests the condition for (char)Keys.Enter. Why is this? How can I make the form take KeyPress for keys other than enter?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
WillumMaguire
  • 537
  • 2
  • 10
  • 21
  • 1
    Set a breakpoint on the first `if` - does execution break on any keypress? If so, investigate `e` for clues as to why your conditions aren't being met. – overslacked Dec 27 '12 at 23:27

2 Answers2

3

Try overriding the KeyDown method instead:

protected override void OnKeyDown(KeyEventArgs e) {
  if (e.KeyCode == Keys.Up || e.KeyCode == Keys.W) {
    picPaddle.Top -= 10;
  } else if (e.KeyCode == Keys.Down || e.KeyCode == Keys.S) {
    picPaddle.Top += 10;
  }

  base.OnKeyDown(e);
}

Also see What's the difference between KeyDown and KeyPress in .NET?

Community
  • 1
  • 1
LarsTech
  • 80,625
  • 14
  • 153
  • 225
-1

the KeyPress event works when the control has the focus. The keydown event allways works . => intercept the keydown event

Stephane Halimi
  • 408
  • 3
  • 5
  • Per the question, the KeyPress event of the form was being used (along with the KeyPreview property being set to true). KeyDown, KeyPress and KeyUp are all available to the form in this case. – overslacked Dec 28 '12 at 00:56