表单中所有控件的事件处理程序
EventHandler for all controls in form
在我的代码中,我想在某些控件获得焦点时执行某些操作。因此,我想知道是否有任何方法可以将所有控件添加到处理程序并在处理程序函数内部执行所需的操作,而不是为每个控件设置一个处理程序。
我有这个:
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)
}
在我的代码中,我想在某些控件获得焦点时执行某些操作。因此,我想知道是否有任何方法可以将所有控件添加到处理程序并在处理程序函数内部执行所需的操作,而不是为每个控件设置一个处理程序。
我有这个:
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)
}