【问题标题】:Adding methods to two events at the same time同时为两个事件添加方法
【发布时间】:2012-03-20 23:09:04
【问题描述】:

我制作了一个自定义按钮,每当我添加 Click 事件时,我都需要添加一个 PreviewKeyDown 事件。到目前为止我得到的是:

public new event EventHandler Click { 
    add { 
        base.Click += value; 
        foreach (Control i in Controls) { 
            i.Click += value; 
        } 
    } 
    remove { 
        base.Click -= value; 
        foreach (Control i in Controls) { 
            i.Click -= value; 
        } 
    } 
} 

这会将点击事件添加到所有内容,但我需要在 winforms 中同时向点击事件和 PreviewKeyDown 事件添加一个方法。它是一个自定义按钮,所以它可以在有人点击进入时执行一个方法

如果有不清楚的地方,请发表评论并澄清

【问题讨论】:

  • 你不能在add 部分也说base.PreviewKeyDown = value 吗?
  • 这不起作用,但它的一个变体确实......我做了 base.PreviewKeyDown += new PreviewKeyDownEventHandler(value);谢谢
  • 这行得通。在处理程序中,您必须将 EventArgs e 转换为 MouseEventArgsPreviewKeyDownEventArgs 才能对它们做一些有用的事情。
  • @OlivierJacot-Descombes 仅使用 EventArgs e 工作正常,不过谢谢

标签: c# events event-handling click keypress


【解决方案1】:

完成的代码:

public new event EventHandler Click {
add {
base.Click += value;
base.PreviewKeyDown += new PreviewKeyDownEventHandler(value);
foreach (Control i in Controls) {
i.Click += value;
i.PreviewKeyDown += new PreviewKeyDownEventHandler(value);
}
}
remove {
//same code with -= instead of +=, but the previewkeydown event is excluded because i couldnt find a way to remove it.
}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-16
    相关资源
    最近更新 更多