下面是我的整个代码,没有其他可能会干扰代码的形式,类等。我刚刚写了这个测试。请注意,我知道我有为什么KeyDown事件不起作用?
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");
}
}
}
}
可以毫不的KeyPreview工作也如果一切是正确的! –
您是否在Form1_KeyDown方法中放置了一个调试器,以查看代码是否正在执行? –
KeyPreview是一个VB6属性,它的行为就像它在VB6时代所做的一样。这是怪异的,它不会触发导航键的事件。像Enter一样。只是不要使用它并选择适当的.NET方式,重写表单的ProcessCmdKey()方法。 –