Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在用户控件中捕获Keyup事件?_C#_Winforms_Events_Keyup - Fatal编程技术网

C# 如何在用户控件中捕获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() {

我想在usercontrol中捕获父窗体的keyup事件。我使用ProcessCmdKey,但它只给我keydown事件,而不会在keydup事件中引发。我怎么做

更新:我想捕捉表单的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 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。但事件不会发生。