Jamie Jamie - 1 month ago 12
C# Question

C# button up/down/left/right not detected

A week ago I used this for detecting the

up/down/left/right keys
in my
wpf application:

private void Invaders_KeyDown(object sender, KeyEventArgs e)
{
MessageBox.Show(e.KeyCode.ToString());
switch (e.KeyCode.ToString())
{
case "Up":
MessageBox.Show("Up");
break;
case "Down":
MessageBox.Show("Down");
break;
case "Left":
MessageBox.Show("Left");
break;
case "Right":
MessageBox.Show("Right");
break;
}
}


But today I started a new application and this does not work anymore? It detects everything except
up/down/left/right
. What could be going on here?

Answer

Link Invaders_PreviewKeyDown to KeyDown event of your buttons. Don't using string for check. That code should is:

private void Invaders_PreviewKeyDown(object sender, KeyEventArgs e)
{
     MessageBox.Show(e.KeyCode.ToString());
     switch (e.KeyCode)
     {
        case Keys.Up:
           MessageBox.Show("Up");
           break;
        case Keys.Down:
           MessageBox.Show("Down");
           break;
        case Keys.Left:
          MessageBox.Show("Left");
          break;
        case Keys.Right:
          MessageBox.Show("Right");
        break;
        default:
          // Do something with default
          break;
     }
}
Comments