C# 检测用户控件内部控件焦点
是否可以检测控件是否已在用户控件中获得焦点?我的意思不是我们在设计时添加到用户控件中的一些控件,而是在表单上使用用户控件后添加哪些控件。一个典型的例子是面板。我的用户控件就像一个面板,我想检测我的用户控件上的一个包含(嵌套)控件何时得到我所做事情的任何焦点C# 检测用户控件内部控件焦点,c#,.net,user-controls,C#,.net,User Controls,是否可以检测控件是否已在用户控件中获得焦点?我的意思不是我们在设计时添加到用户控件中的一些控件,而是在表单上使用用户控件后添加哪些控件。一个典型的例子是面板。我的用户控件就像一个面板,我想检测我的用户控件上的一个包含(嵌套)控件何时得到我所做事情的任何焦点 谢谢大家 我将采用的方法是,当创建UserControl而您不处于设计模式时,在用户控件中的每个控件之间循环,向其GotFocus事件添加钩子,并将钩子指向UserControl的方法(例如ChildControlGotFocus)这反过来会
谢谢大家 我将采用的方法是,当创建UserControl而您不处于设计模式时,在用户控件中的每个控件之间循环,向其GotFocus事件添加钩子,并将钩子指向UserControl的方法(例如ChildControlGotFocus)这反过来会引发一个事件,用户控件的宿主可以使用该事件 例如,下面是实现此功能的示例UserControl:
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
if (!this.DesignMode)
{
RegisterControls(this.Controls);
}
}
public event EventHandler ChildControlGotFocus;
private void RegisterControls(ControlCollection cControls)
{
foreach (Control oControl in cControls)
{
oControl.GotFocus += new EventHandler(oControl_GotFocus);
if (oControl.HasChildren)
{
RegisterControls(oControl.Controls);
}
}
}
void oControl_GotFocus(object sender, EventArgs e)
{
if (ChildControlGotFocus != null)
{
ChildControlGotFocus(this, new EventArgs());
}
}
}
我处理这个问题的方法是,当用户控件被创建并且您不在设计模式下时,在用户控件中的每个控件之间循环,向它们的GotFocus事件添加钩子,并将钩子指向用户控件的一个方法(比如ChildControlGotFocus)这反过来会引发一个事件,用户控件的宿主可以使用该事件 例如,下面是实现此功能的示例UserControl:
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
if (!this.DesignMode)
{
RegisterControls(this.Controls);
}
}
public event EventHandler ChildControlGotFocus;
private void RegisterControls(ControlCollection cControls)
{
foreach (Control oControl in cControls)
{
oControl.GotFocus += new EventHandler(oControl_GotFocus);
if (oControl.HasChildren)
{
RegisterControls(oControl.Controls);
}
}
}
void oControl_GotFocus(object sender, EventArgs e)
{
if (ChildControlGotFocus != null)
{
ChildControlGotFocus(this, new EventArgs());
}
}
}
谢谢我真的很感激你做的这件事。谢谢。我真的很感激你做的这件事。