问题
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