窗体中所有控件的事件处理程序



在我的代码中,我想在某些控件聚焦时执行一些操作。因此,与其为每个控件设置一个处理程序,我想知道是否有任何方法将所有控件添加到处理程序并在处理程序函数内执行所需的操作。

我有这个:

    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
        {
           ...
        }
    }

这可能吗?我该怎么做?多谢。

在窗体或面板中迭代控件并订阅其 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) 
    }

相关内容

  • 没有找到相关文章

最新更新