为什么KeyDown事件不起作用?

时间:2014-02-18 12:36:03

标签: c#

下面是我的整个代码,没有其他形式,类等可能会干扰代码。我刚刚写了这个用于测试。请注意,我知道我有

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

3 个答案:

答案 0 :(得分:0)

IsInputKey属性设置为true。

Control.KeyDown Event

答案 1 :(得分:0)

您从未订阅过KeyDown个活动。请查看以下LINQPad代码段:

public void Main()
{
    Application.Run(new MyForm());
}

public class MyForm : Form
{
    public MyForm()
    {
        this.KeyDown += this.OnKeyDown;
    }

    public void OnKeyDown(object sender, KeyEventArgs e)
    {
        e.Dump();
    }
}

答案 2 :(得分:0)

您可以覆盖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);
    }
相关问题