我想在usercontrol中捕获父窗体的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);
}
}
答案 0 :(得分:1)
您可以在UserControl的OnHandleCreated覆盖方法中为父窗体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);
}