C# 如何在用户控件中捕获Keyup事件?
我想在usercontrol中捕获父窗体的keyup事件。我使用ProcessCmdKey,但它只给我keydown事件,而不会在keydup事件中引发。我怎么做 更新:我想捕捉表单的keyup事件。因为Control.KeyUp在控件被聚焦时被触发C# 如何在用户控件中捕获Keyup事件?,c#,winforms,events,keyup,C#,Winforms,Events,Keyup,我想在usercontrol中捕获父窗体的keyup事件。我使用ProcessCmdKey,但它只给我keydown事件,而不会在keydup事件中引发。我怎么做 更新:我想捕捉表单的keyup事件。因为Control.KeyUp在控件被聚焦时被触发 public partial class ExtendedButton : Button { const int WM_KEYDOWN = 0x100; public ExtendedButton() {
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 override方法中为父窗体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);
}
为什么这么复杂?请参阅@user2864740我想在usercontrol中使用keyup事件,而不是表单中的。。仍然不确定复杂的原因是什么。@user2864740我想捕捉形式的keycup事件。因为Control.KeyUp是在控件处于焦点时引发的。您可能已经保留了一个要向下冒泡的控件列表。有点像程序如何保持所有窗口的标题栏处于活动状态,无论哪个窗口有焦点。发生了什么?有什么错误吗?您是否已将父窗体的
KeyPreview
属性设置为true?是,我已设置KeyPreview属性。没有错误,但未引发keyup事件。是否尝试调试代码?OnHandleCreated
事件是否被触发?用户控件无法为父窗体向上键事件创建处理程序,则不会激发该事件。尝试在parentForm=(Form)parent上放置断点代码>行并调试它在parent
object.OnHandleCreated中存储的值,并且parentForm的值为true。但事件不会发生。