滴水静禅天
扫描关注滴水静禅天

扫码加微信:-)

C#自动化生成控件并共用事件行为

滴水静禅天2017-10-25信息计算 1542
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;namespace ButtonArray{
    public partial class frm1 : Form    {
        private Button[] btns;
        public frm1()
        {
            InitializeComponent();
        }
   
        private void Form1_Load(object sender, EventArgs e)
        {
            //自动生成一个拨号盘            int x0 = 120, y0 = 80, w = 50, h = 50, wc = 40, hc = 30;
             btns = new Button[12];
             for (int i = 0; i < 4; i++) //行数             {
                 for (int j = 0; j < 3; j++)//列数                 {
                     
                     int index = i * 3 + j;
                     string btnName = string.Format("button{0}", index);
                     btns[index] = new Button();
                     
                     btns[index].Parent = groupBox1;
                     btns[index].Location = new Point(x0 + j * (w + wc), y0 + i * (h + hc));
                     btns[index].Size = new Size(w, h);
                     btns[index].Name = btnName;
                     this.btns[index].Click += new System.EventHandler(this.button_Click);
                     btns[index].Font = new System.Drawing.Font(btns[index].Font.FontFamily,14);
                     btns[index].Enabled = true;
                     if (index != 9 && index != 11)
                     {
                         btns[index].Text = index.ToString();
                     }
                     else if (index == 9)
                     {
                         btns[index].Text = "#";
                     }
                     else                     {
                         btns[index].Text = "*";
                     }
                   
                 }
             }
            
        }
        private void button_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;
            btn.BackColor = Color.Red;
        }
    }
}

blob.png

发表评论