2014-02-18 84 views
1

下面是我的整个代码,没有其他可能会干扰代码的形式,类等。我刚刚写了这个测试。请注意,我知道我有为什么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"); 
     } 
    } 
} 
} 
+0

可以毫不的KeyPreview工作也如果一切是正确的! –

+0

您是否在Form1_KeyDown方法中放置了一个调试器,以查看代码是否正在执行? –

+1

KeyPreview是一个VB6属性,它的行为就像它在VB6时代所做的一样。这是怪异的,它不会触发导航键的事件。像Enter一样。只是不要使用它并选择适当的.NET方式,重写表单的ProcessCmdKey()方法。 –

回答

0

IsInputKey属性设置为true。

Control.KeyDown Event

+1

这段代码是什么工作,谢谢! protected override bool IsInputKey(Keys keyData) if(keyData == Keys.Enter) { MessageBox.Show(“True”); 返回true; } else { return base.IsInputKey(keyData); } } – user1114503

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