为什么我的KeyPressEvent无法与Right/Left/Up/Down一起使用? [英] Why does my KeyPressEvent not work with Right/Left/Up/Down?

查看:137
本文介绍了为什么我的KeyPressEvent无法与Right/Left/Up/Down一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,我试图查看用户是否按了右键,以便玩家向右移动,但是当我尝试操作时,它没有注册按键:

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

它不显示消息框

这对左/上/下也不起作用

This doesn't work for Left/Up/Down either

但是,如果我将其替换为

However, if I replace it with

if(e.KeyChar == Convert.ToChar(Keys.Space))

有效.

我做错什么了吗?

推荐答案

您应使用KeyDown事件,例如箭头:

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)
    {
    }
}

箭头键不是字符,因此不使用KeyPressed.

Arrow keys are not characters, so KeyPressed is not used for them.

这篇关于为什么我的KeyPressEvent无法与Right/Left/Up/Down一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆