KeyPress F1不起作用C#

Wer*_*ver 7 c# keypress

我正在设计一个设备应用程序.Compact Framework 2.0

我希望用户按F1导航到下一个屏幕,但它不起作用.

似乎无法找到解决方案.

可能吗?

这就是我通常使用Keypress的方式:

这有效:

        if (e.KeyChar == (char)Keys.M)
        {
            MessageBox.Show("M pressed");
            e.Handled = true;
        }
Run Code Online (Sandbox Code Playgroud)

这不起作用:

        if (e.KeyChar == (char)Keys.F1)
        {
            MessageBox.Show("F1 pressed");
            e.Handled = true;
        }
Run Code Online (Sandbox Code Playgroud)

Mic*_* DN 7

请参阅

您可以覆盖ProcessCmdKey表单类的方法,并用于keyData == Keys.F1检查F1是否被按下.以上链接的示例如下.

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    if (keyData == Keys.F1)
    {
        MessageBox.Show("You pressed the F1 key");
        return true;    // indicate that you handled this keystroke
    }

    // Call the base class
    return base.ProcessCmdKey(ref msg, keyData)
}
Run Code Online (Sandbox Code Playgroud)


小智 6

尝试这个

private void Form1_Load(object sender, EventArgs e)
{
    this.KeyPreview = true;
    this.KeyDown += new KeyEventHandler(Form1_KeyDown);
}

void Form1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode.ToString() == "F1")
    {
        MessageBox.Show("F1 pressed");
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 虽然这确实有效,但我真的认为您应该考虑任何其他答案 - 使用枚举值,而不是比较字符串。 (2认同)