2011-12-11 34 views
1

是否有可能检测控件是否已获得用户控件的焦点?我的意思不是我们在设计时添加到用户控件中的某些控件,而是控制我们在表单上使用用户控件后添加它们的控件。一个意思是面板的例子。我的用户控件就像面板一样,我想要检测用户控件上的包含(嵌套)控件何时获得我关注的任何焦点。检测用户控件内部控件焦点

谢谢你们!

回答

1

我会这样做的方式是当UserControl被创建并且您不处于设计模式时,循环遍历用户控件中的每个控件,将钩子添加到它们的GotFocus事件并将钩子指向UserControl(如ChildControlGotFocus)反过来引发用户控件的主机可以使用的事件。

例如,下面是实现该功能的用户控件样品:

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()); 
     } 
    } 
} 
+0

感谢。我非常感谢你所做的这件事。 – MahanGM