KeyPreview :Gets or sets a value indicating whether the form will receive key events before the event is passed to the control that has focus
public Form1()
{
InitializeComponent();
this.KeyPreview = true;
}
private void OnKeyDown(object sender, KeyEventArgs e)
{
string shortCutKeyF12 = "F12";
if (e.KeyCode.ToString() == shortCutKeyF12)
{
MessageBox.Show("F12 catched");
}
}
private void textBoxKeyDown(object sender, KeyEventArgs e)
{
MessageBox.Show("TextBox handled");
}
此时在Form上的子控件如TextBox里按下F12键,Form的OnKeyDown可以捕获并且处理,然后才处理textBox 自己的事件。
当然我们也可以使textBox自己的OnKeyDown不被处理,只要在处理完Form的OnKeyDown后,设置属性
e.Handled = true;
public Form1()
{
InitializeComponent();
this.KeyPreview = true;
}
private void OnKeyDown(object sender, KeyEventArgs e)
{
string shortCutKeyF12 = "F12";
if (e.KeyCode.ToString() == shortCutKeyF12)
{
MessageBox.Show("F12 catched");
}
e.Handled = true;
}
private void textBoxKeyDown(object sender, KeyEventArgs e)
{
MessageBox.Show("TextBox handled");
}