請看代碼: 貼出執行效果圖: ...
請看代碼:
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; //Color結構體所在位置 6 using System.Linq; 7 using System.Text; 8 using System.Threading.Tasks; 9 using System.Windows.Forms; 10 using System.Reflection; //反射必須引用此命名空間 11 12 namespace ReflectColorStructDemo 13 { 14 public partial class MainForm : Form 15 { 16 //窗體初始化 17 public MainForm() 18 { 19 InitializeComponent(); 20 21 this.Location = new Point(0, 0); //窗體左上角得屏幕坐標 22 this.Size = SystemInformation.WorkingArea.Size; //窗體尺寸,需要修改窗體的StartPosition屬性為Manual,即:手動 23 24 //窗體第一次載入事件處理方法:Lambda語法 25 this.Load += (object sender, EventArgs e) => 26 { 27 Type type = typeof(Color); 28 PropertyInfo[] propertyInfo = type.GetProperties(BindingFlags.Public | BindingFlags.Static); //獲取Color類型的所有公有且是靜態的屬性 29 30 int x, y, w, h, index; 31 32 x = 2; //初始x坐標 33 y = 2; //初始y坐標 34 w = 87; //加入面板中的Label控制項的寬度 35 h = 65; //高度 36 37 index = 0; //計數器,反射得到propertyInfo數組的元素數 38 39 int col = 15; //列數 40 int line = propertyInfo.Length % col > 0 ? propertyInfo.Length / col + 1 : propertyInfo.Length / col; //行數 41 42 //外層迴圈控制行 43 for (int i = 0; i < line; i++) 44 { 45 //內層迴圈控制列 46 for (int j = 0; j < col && index < propertyInfo.Length; j++) 47 { 48 Label label = new Label(); 49 label.Location = new Point(x, y); 50 label.Size = new Size(w, h); 51 52 label.BackColor = Color.FromName(propertyInfo[index].Name); //設置Label控制項背景色 53 54 label.Text = string.Concat((index + 1).ToString(), '\n', propertyInfo[index].Name); //顯式文本 55 56 x += w + 2; //x坐標後移 57 index++; //計數器自增 58 59 this.panel1.Controls.Add(label); //將新標簽加入面板,窗體需要添加一個Panel控制項且填充窗體 60 } 61 62 x = 2; //內層迴圈完畢後,歸位x坐標 63 y += h + 2; //y坐標下移,2表示控制項間距 64 } 65 }; 66 } 67 } 68 }
貼出執行效果圖: