如何在C#.NET表单上捕获按键

我有一个包含很多控件的父窗体。 我想要做的是过滤该表格的所有按键。 麻烦的是,如果焦点在表单上的一个控件上,那么父表单没有获得按键事件,那么如何捕获按键事件?

在表单上将KeyPreview设置为true,您将捕获它们: MSDN

myForm : Form { public ChildForm() { KeyPress += KeyPressHandler; } public KeyPressHandler(object sender, KeyPressEventArgs e) { if (_parent != null) { _parent.NotifyKeyPress(e); } } } 

在您的情况下,这将更多的套房

 protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { if (keyData == Keys.F1) { MessageBox.Show("You pressed the F1 key"); return true; // indicate that you handled this keystroke } // Call the base class return base.ProcessCmdKey(ref msg, keyData) }