C# 试图检测按键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12981024/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:12:08  来源:igfitidea点击:

Trying to detect keypress

c#keypress

提问by Adam_MOD

I made a method that detects when a key is pressed, but its not working! Heres my code

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

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

I also tried to make a keyeventhandler but, it sais "cannot assign to key detect because it is a method group"

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

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

采纳答案by Ravindra Bagale

Use keypress event like this:

像这样使用按键事件:

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

回答by Chibueze Opata

You are looking for this.KeyPress. See How to Handle Keypress Events on MSDN.

您正在寻找this.KeyPress. 请参阅如何处理 MSDN 上的按键事件

回答by nrofis

Try to use the KeyDownevent.

尝试使用该KeyDown事件。

Just see KeyDownin MSDN

KeyDownMSDN上看到

回答by Jordan Miller

1) Go to your form's Properties

1) 转到表单的属性

2) Look for the "Misc" section and make sure "KeyPreview" is set to "True"

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

3) Go to your form's Events

3) 转到表单的事件

4) Look for the "Key" section and double click "KeyDown" to generate a function to handle key down events

4) 找到“Key”部分,双击“KeyDown”,生成处理按键按下事件的函数

Here is some example code:

下面是一些示例代码:

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