【问题标题】:Trying to detect keypress试图检测按键
【发布时间】:2012-10-10 11:13:50
【问题描述】:

我做了一个方法来检测何时按下一个键,但它不起作用!这是我的代码

void KeyDetect(object sender, KeyEventArgs e)
{ 
    if (e.KeyCode == Keys.W && firstload == true)
    {
        MessageBox.Show("Good, now move to that box over to your left");
        firstload = false;
    }
}

我也尝试过创建一个 keyeventhandler,但它说“无法分配给键检测,因为它是一个方法组”

public Gwindow()
{
    this.KeyDetect += new KeyEventHandler(KeyDetect);
    InitializeComponent();    
}

【问题讨论】:

    标签: c# keypress


    【解决方案1】:

    像这样使用按键事件:

    private void Form1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyCode == Keys.F1 && e.Alt)
        {
            //do something
        }
    }
    

    【讨论】:

    • ...你确定应该是一个=吗?另外,我认为您不需要额外的括号。
    • 很确定== 符号是指检查相等性而不是赋值。
    【解决方案2】:

    1) 转到表单的属性

    2) 查找“Misc”部分并确保“KeyPreview”设置为“True”

    3) 转到表单的事件

    4) 查找“Key”部分并双击“KeyDown”以生成处理按键事件的函数

    下面是一些示例代码:

        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            Console.WriteLine("You pressed " + e.KeyCode);
            if (e.KeyCode == Keys.D0 || e.KeyCode == Keys.NumPad0)
            {
                //Do Something if the 0 key is pressed (includes Num Pad 0)
            }
        }
    

    【讨论】:

      【解决方案3】:

      您正在寻找this.KeyPress。见How to Handle Keypress Events on MSDN

      【讨论】:

        【解决方案4】:

        尝试使用KeyDown 事件。

        只需在MSDN 中查看KeyDown

        【讨论】:

        • 不完全是我想要的。无论如何,谢谢!
        【解决方案5】:

        做事

        if (Input.GetKeyDown("/* KEYCODE HERE */"))
        {
            /* CODE HERE */
        }
        

        【讨论】:

          猜你喜欢
          • 2012-10-11
          • 2016-08-01
          • 1970-01-01
          • 2013-08-17
          • 1970-01-01
          • 1970-01-01
          • 2014-07-27
          • 2013-12-14
          相关资源
          最近更新 更多