ActiveControl如何能得到其内部的其它的控件?

解决方案 »

  1.   

    因为splitContainer也是控件Control,所以窗体的ActiveControl为splitContainer也是合理的,但是可能我们对这样的窗口控件为ActiveControl并不太喜欢,我们需要的是像TextBox,Button等最基本的控件为ActiveControl,所以可以如下获取窗体的ActiveControl:protected override void OnClick(EventArgs e)
    {
    Control activeControl = this.getActiveControl();
    base.OnClick(e);
    }private Control getActiveControl()
    {
    Control activeControl = this.ActiveControl;
    while ((activeControl as ContainerControl) != null)
    {
    activeControl = (activeControl as ContainerControl).ActiveControl;
    }
    return activeControl;
    }
      

  2.   

    ActiveControl是相对于容器的,而SplitContainer本身也是一个容器,所以要递归遍历
    参考如下代码
    public Control LeafActiveControl(ContainerControl AParent)
    {
        if (AParent == null) return null;
        if (AParent.ActiveControl is ContainerControl)
            return LeafActiveControl(AParent.ActiveControl as ContainerControl);
        return AParent.ActiveControl;
    }//test
    private void timer1_Tick(object sender, EventArgs e)
    {    
        Control vLeafActiveControl = LeafActiveControl(this);
        if (vLeafActiveControl != null)
            Text = vLeafActiveControl.Name;
        else Text = "null";
    }