2016年9月4日 星期日

[C#] Windows Form 元件搜尋



C# 主要元件如下圖, 如果需要找尋元件名稱或是標籤名稱可以透過以下程式方法


namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            //第一層的 WinForm 的所有元件
            foreach (Control Layer1 in this.Controls)
            {
                //過濾第二層的 TabControl
                if (Layer1.GetType().Name == "TabControl")
                {
                    //第二層的 TabControl 的所有元件
                    foreach (Control Layer2 in Layer1.Controls)
                    {
                        //過濾第三層的 TabPage
                        if (Layer2.GetType().Name == "TabPage")
                        {
                            //第三層的 TabPage 的所有元件
                            foreach (Control Layer3 in Layer2.Controls)
                            {
                                //過濾第四層的 TableLayoutPanel
                                if (Layer3.GetType().Name == "TableLayoutPanel")
                                {
                                    //第四層的 TableLayoutPanel 的所有元件
                                    foreach (Control Layer4 in Layer3.Controls)
                                    {
                                        Console.WriteLine(Layer4.GetType().Name);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

程式檔案:
Link

沒有留言:

張貼留言