繁体   English   中英

如何制作一个为表单中的每个控件添加事件处理程序的组件?

[英]How to make a component that adds an event handler to each control in a Form?

我刚刚创建了一个使用ToolTip控件的 Windows 窗体,我ToolTip想到该组件为窗体上的每个其他控件提供设计时属性。

我知道对于属性,您可以简单地实现IExtender接口,但这可以扩展到事件吗? 如果是这样怎么办?

我使用递归函数向所有控件添加事件处理程序,即使它们嵌套在网格或面板等容器内

通常,我将此功能用于很多事情,即使我想在获得焦点/离开时添加自定义背景颜色。

private void addEventhandler(Control Parent) {

    if (Parent.Controls.Count > 0) {
        //===>If the curren control is a container!
        foreach(Control iChild in Parent.Controls) {
            addEventhandler(iChild);//Call it self
        }
    } else {//Individual control
        //===>TODO: Add here all your events handler to Parent variable.

        Parent.Click += new EvenHandler(delegate(object sender,object e){
                                            MessageBox.Show("Hello");
                                            });

        //==>If you whant to filter by control type you can do this
        if(Parent is TextBox){
            ((TextBox)Parent).Text = "Hi! XD";
        }
    }
}

像这样实现这段代码

addEventhandler(this);//If you want to add the events handler to all controls in your form

addEventhandler(myGridControl);//To specific grid

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM