我想在用户控件中捕获父窗体的keyup事件。我使用ProcessCmdKey,但它只给了我keydown事件,而不会引发keyup事件。我该怎么做?
更新:我想捕获窗体的keyup事件。因为Control.keyup在控件聚焦时引发。
public partial class ExtendedButton : Button
{
const int WM_KEYDOWN = 0x100;
public ExtendedButton()
{
InitializeComponent();
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (msg.Msg == WM_KEYUP && keyData == (Keys.NumPad0))
{
MessageBox.Show("hi");
}
return base.ProcessCmdKey(ref msg, keyData);
}
}
您可以在UserControl的OnHandleCreated覆盖方法中为Parent Form KeyUp创建处理程序。
试试这个代码
Form parentForm = null;
private void ParentForm_KeyUp(object sender, KeyEventArgs e)
{
MessageBox.Show("HI");
}
protected override void OnHandleCreated(EventArgs e)
{
if (DesignMode)
return;
base.OnHandleCreated(e);
object parent = this;
while (true)
{
parent = ((Control)parent).Parent;
if (parent.GetType().BaseType.Name == "Form")
break;
}
parentForm = (Form)parent;
parentForm.KeyUp -= new KeyEventHandler(this.ParentForm_KeyUp);
parentForm.KeyUp += new KeyEventHandler(this.ParentForm_KeyUp);
}