尝试检测按键操作

4
我写了一个检测按键是否按下的方法,但它不起作用!这是我的代码。
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,但是它显示“无法分配到key detect,因为它是一个方法组”。

public Gwindow()
{
    this.KeyDetect += new KeyEventHandler(KeyDetect);
    InitializeComponent();    
}
5个回答

9

像这样使用keypress事件:

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

1
你确定应该只有一个=吗?此外,我认为你不需要额外的括号。 - anon
2
相信 == 符号是用于检查相等性而不是赋值。 - Ron Zhang

6

1)进入您表单的“属性”

2)寻找“其他”部分,确保“KeyPreview”设置为“True”

3)进入您表单的“事件”

4)查找“键”部分,并双击“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)
        }
    }

1

1

尝试使用 KeyDown 事件。

只需查看 MSDN 中的 KeyDown 即可。


不是我想要的,但还是谢谢! - Adam_MOD

1

只需要做

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接