未检测到C#按钮上/下/左/右

时间:2016-10-20 09:35:37

标签: c# wpf

一周前我用它来检测我的up/down/left/right keys wpf申请:

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;
    }
}

但是今天我开始了一个新的应用程序,这不再适用了吗?它会检测除up/down/left/right以外的所有内容。可能会发生什么?

1 个答案:

答案 0 :(得分:0)

将Invaders_PreviewKeyDown链接到按钮的KeyDown事件。不要使用字符串进行检查。那段代码应该是:

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;
     }
}