Joe
Joe

Reputation: 538

Why does my KeyPressEvent not work with Right/Left/Up/Down?

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?

Upvotes: 2

Views: 5334

Answers (2)

Szymon
Szymon

Reputation: 43023

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.

Upvotes: 5

Arrow Keys are in keyUp event they are:

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

They are not triggered by KeyPressEventArgs.

Upvotes: 2

Related Questions