using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Windows.Forms;public class WindowsForm : System.Windows.Forms.Form { public static void Main() { Application.Run(new WindowsForm()); } public WindowsForm() { this.KeyPreview = true; // 注意这句 this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Form1_KeyDown);
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;public class WindowsForm : System.Windows.Forms.Form
{
public static void Main()
{
Application.Run(new WindowsForm());
} public WindowsForm()
{
this.KeyPreview = true; // 注意这句
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Form1_KeyDown);
}
private void Form1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
MessageBox.Show("key down");
}
}
事件处理程序接收一个 KeyEventArgs 类型的参数,它包含与此事件相关的数据。下列 KeyEventArgs 属性提供特定于此事件的信息。属性 说明
Alt 获取一个值,该值指示是否曾按下 ALT 键。
Control 获取一个值,该值指示是否曾按下 CTRL 键。
Handled 获取或设置一个值,该值指示是否处理过此事件。
KeyCode 获取 KeyDown 或 KeyUp 事件的键盘代码。
KeyData 获取 KeyDown 或 KeyUp 事件的键数据。
KeyValue 获取 KeyDown 或 KeyUp 事件的键盘值。
Modifiers 获取 KeyDown 或 KeyUp 事件的修饰符标志。这指示曾按下哪一个修饰符键(CTRL、SHIFT 和 ALT)的组合。
Shift 获取一个值,该值指示是否曾按下 SHIFT 键。 备注
键事件按下列顺序发生: KeyDown
KeyPress
KeyUp
要仅在窗体级别处理键盘事件并且不允许其他控件接收键盘事件,请将窗体的 KeyPress 事件处理方法中的 KeyPressEventArgs.Handled 属性设置为 true。某些键,如 TAB、RETURN、ESCAPE 和箭头键,由控件自动处理。为使这些键引发 KeyDown 事件,必须在窗体上的每个控件中重写 IsInputKey 方法。用于重写 IsInputKey 的代码需要确定是否按下了某一个特殊键,并且需要返回一个 true 值