2

In C#, I am trying to see if the user presses the right key so that a player moves right, but when I try it, it does not register the keypress:

private void KeyPressed(object sender, KeyPressEventArgs e)
{
      if(e.KeyChar == Convert.ToChar(Keys.Right))
      {
              MessageBox.Show("Right Key");
      } 
} 

It does not display the MessageBox

This doesn't work for Left/Up/Down either

However, if I replace it with

if(e.KeyChar == Convert.ToChar(Keys.Space))

It works.

Am I doing something wrong?

Joe
  • 528
  • 5
  • 19
  • 2
    It's probably because `Right` is not a character. I believe you're looking for something pertaining to command keys. – Logarr Nov 06 '13 at 22:47
  • 1
    I'd attach a debugger and see a) is the event even being fired? b) What the value of `e.KeyChar` is and c) what the value of `Keys.Right` is. – Mike Christensen Nov 06 '13 at 22:49

2 Answers2

5

You should use KeyDown event, e.g. for arrows:

private void KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Down || e.KeyCode == Keys.Up || e.KeyCode == Keys.Left || e.KeyCode == Keys.Right)
    {
    }
}

Arrow keys are not characters, so KeyPressed is not used for them.

Szymon
  • 42,577
  • 16
  • 96
  • 114
2

Arrow Keys are in keyUp event they are:

Keys.Up, Keys.Down, Keys.Left, Keys.right

They are not triggered by KeyPressEventArgs.