Aldridge1991
Aldridge1991

Reputation: 1367

EventHandler for all controls in form

In my code I want to perform some actions when some controls are focused. So instead of having one handler for each control i was wondering if there could be any way of adding all controls to the handler and inside the handler function perform the desired action.

I have this:

    private void tb_page_GotFocus(Object sender, EventArgs e)
    {
        tb_page.Visible = false;
    }

    private void tb_maxPrice_GotFocus(Object sender, EventArgs e)
    {
        tb_maxPrice.Text = "";
    }

    private void tb_maxPrice_GotFocus(Object sender, EventArgs e)
    {
        tb_maxPrice.Text = "";
    }

I want this:

    private void AnyControl_GotFocus(Object sender, EventArgs e)
    {
        if(tb_page.isFocused == true)
        {
           ...
        }
        else if (tb_maxPrice.isFocused == true)
        {
           ...
        }
        else
        {
           ...
        }
    }

Is this possible? How could I do it? Thanks a lot.

Upvotes: 0

Views: 290

Answers (1)

The One
The One

Reputation: 4784

Iterate your controls in your form or panel and subscribe to their GotFocus Event

private void Form1_Load(object sender, EventArgs e)
    {
        foreach (Control c in this)
        {
            c.GotFocus += new EventHandler(AnyControl_GotFocus);
        }
    }

void AnyControl_GotFocus(object sender, EventArgs e)
    {
       //You'll need to identify the sender, for that you could:

       if( sender == tb_page) {...}

       //OR:
       //Make sender implement an interface
       //Inherit from control
       //Set the tag property of the control with a string so you can identify what it is and what to do with it
       //And other tricks
       //(Read @Steve and @Taw comment below) 
    }

Upvotes: 1

Related Questions