I have a form that I want to know which control on it has focus.
How can I do this? Best solution I have seen has me iterating all the controls on the screen. While doable, it seems like a lot of work just to know which control has the focus.
I have a form that I want to know which control on it has focus.
How can I do this? Best solution I have seen has me iterating all the controls on the screen. While doable, it seems like a lot of work just to know which control has the focus.
You can either do what thelost said, or you can implement your own form base class to handle the task for you.
public class BaseForm : Form
{
public BaseForm()
{
this.Load += new EventHandler(BaseForm_Load);
}
void BaseForm_Load(object sender, EventArgs e)
{
this.HandleFocusTracking(this.Controls);
}
private void HandleFocusTracking(ControlCollection controlCollection)
{
foreach (Control control in controlCollection)
{
control.GotFocus += new EventHandler(control_GotFocus);
this.HandleFocusTracking(control.Controls);
}
}
void control_GotFocus(object sender, EventArgs e)
{
_activeControl = sender as Control;
}
public virtual Control ActiveControl
{
get { return _activeControl; }
}
private Control _activeControl;
}
It is impossible to avoid a control iteration, but if you did it this way the iteration will only happen once instead of every time you want to know the active control. You can then can just call the ActiveControl as per a standard winforms app as follows:
Control active = this.ActiveControl;
The only disadvantage with this is that if you had the requirement to add the new controls at runtime, then you'd have to ensure they were properly hooked up to the control_GotFocus
event.