C# 为什么KeyDown事件不起作用?

C# 为什么KeyDown事件不起作用?,c#,C#,下面是我的全部代码,没有其他可能干扰代码的表单、类等。我只是为了测试而快速写了这篇文章。请注意,我知道我有 this.KeyPreview = true; 这是因为我在查找示例代码时在两个地方都看到了它。代码编译时没有错误。我还使用textBox尝试了这段代码,得到了相同的非工作结果 e.KeyCode==Keys.Enter是不起作用的代码。我还试过其他键,比如W和A。有人知道我还需要做什么吗?使用VS2010 using System; using System.Collections.G

下面是我的全部代码,没有其他可能干扰代码的表单、类等。我只是为了测试而快速写了这篇文章。请注意,我知道我有

this.KeyPreview = true;
这是因为我在查找示例代码时在两个地方都看到了它。代码编译时没有错误。我还使用textBox尝试了这段代码,得到了相同的非工作结果

e.KeyCode==Keys.Enter是不起作用的代码。我还试过其他键,比如W和A。有人知道我还需要做什么吗?使用VS2010

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication5
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        this.KeyPreview = true;
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        this.KeyPreview = true;
    }

    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            MessageBox.Show("True");
        }
    }
}
}
将IsInputKey属性设置为true

您从未订阅过KeyDown事件。检查以下代码段:

您可以按如下方式重写ProcessCmdKey方法:

   protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        if (keyData == Keys.Enter)
        {
            //write your code here
            MessageBox.Show("Enter");
        }
        return base.ProcessCmdKey(ref msg, keyData);
    }

如果一切正常,它也可以在没有按键预览的情况下工作!您是否已在Form1_KeyDown方法中停止调试器,以查看代码是否正在实际执行?KeyPreview是VB6属性,其行为与VB6时代的行为类似。这很奇怪,它不会为导航键触发事件。喜欢进入。只是不要使用它,选择正确的.NET方法,重写表单的ProcessCmdKey方法。这段代码才有效,谢谢!受保护的重写bool IsInputKeyKeykeys keyData{if keyData==Keys。输入{MessageBox.ShowTrue;return true;}否则{return base.IsInputKeyData;}}
   protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        if (keyData == Keys.Enter)
        {
            //write your code here
            MessageBox.Show("Enter");
        }
        return base.ProcessCmdKey(ref msg, keyData);
    }