表单中所有控件的EventHandler

时间:2015-01-27 13:30:46

标签: c# event-handling

在我的代码中,我希望在关注某些控件时执行某些操作。因此,我没有为每个控件设置一个处理程序,而是想知道是否有任何方法可以将所有控件添加到处理程序中,并且在处理函数内部执行所需的操作。

我有这个:

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

我想要这个:

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

这可能吗?我怎么能这样做?非常感谢。

1 个答案:

答案 0 :(得分:1)

在表单或面板中迭代您的控件并订阅他们的GotFocus事件

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) 
    }