我有一个表单,想知道哪个控件当前获得了焦点。
如何实现呢?目前最好的解决方案是遍历屏幕上的所有控件。虽然这种方法可行,但似乎为了只是知道哪个控件获得了焦点而做很多工作。
我有一个表单,想知道哪个控件当前获得了焦点。
如何实现呢?目前最好的解决方案是遍历屏幕上的所有控件。虽然这种方法可行,但似乎为了只是知道哪个控件获得了焦点而做很多工作。
你可以按照thelost所说的做法,或者实现自己的表单基类来处理该任务。
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;
}
无法避免控制迭代,但如果您按照以下方式执行,则迭代仅会发生一次,而不是每次想要了解活动控件时都会发生。然后,您可以像标准的WinForms应用程序一样调用ActiveControl:
Control active = this.ActiveControl;