liuying
2024-11-30 be14322d1b20857082dd47aeb895bd976dca13e0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
 
namespace iWareCC.Common.Helper
{
    public class ControlHelper
    {
        /// <summary>
        /// 根据指定容器和控件名字,获得控件
        /// ((Button) GetControlInstance(this.groupBox4,"button7")).PerformClick();
        /// </summary>
        /// <param name="obj">容器</param>
        /// <param name="strControlName">控件名字</param>
        /// <returns>控件</returns>
        public static object GetControlInstance(Control obj, string strControlName)
        {
            IEnumerator Controls = null;//所有控件
            Control c = null;//当前控件
            Object cResult = null;//查找结果
            Controls = ((Control)obj).Controls.GetEnumerator();
            //if (obj.GetType() == this.GetType())//窗体
            //{
            //    Controls = this.Controls.GetEnumerator();
            //}
            //else//控件
            //{
            //    Controls = ((Control)obj).Controls.GetEnumerator();
            //}
            while (Controls.MoveNext())//遍历操作
            {
                c = (Control)Controls.Current;//当前控件
                if (c.HasChildren)//当前控件是个容器
                {
                    cResult = GetControlInstance(c, strControlName);//递归查找
                    if (cResult == null)//当前容器中没有,跳出,继续查找
                        continue;
                    else//找到控件,返回
                        return cResult;
                }
                else if (c.Name == strControlName)//不是容器,同时找到控件,返回
                {
                    return c;
                }
            }
            return null;//控件不存在
        }
     
    }
}