Abdessabour Mtk
Abdessabour Mtk

Reputation: 3888

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

I was just creating a Windows form that uses a ToolTip control and it occurred to me that this component provides design time properties for every other control on the form.

I know that for properties you can simply implement the IExtender interface but can this be extended to events? If so how to do it?

Upvotes: 0

Views: 296

Answers (1)

MrAlex6204
MrAlex6204

Reputation: 167

I use recursively function to add events hanlder to all controls even if they are nested inside of a container like grids or panels

Normaly I use this function for a lot of things Even if I want to add a custom backgroundcolor when got focus/leave.

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";
        }
    }
}

Implement this code like this

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

addEventhandler(myGridControl);//To specific grid

Upvotes: 1

Related Questions