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

筅森魡賤 提交于 2019-12-14 02:28:11

问题


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?


回答1:


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.




回答2:


Arrow Keys are in keyUp event they are:

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

They are not triggered by KeyPressEventArgs.



来源:https://stackoverflow.com/questions/19824451/why-does-my-keypressevent-not-work-with-right-left-up-down

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!