加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

C# 代码实现控件的添加(按钮)

(2012-06-07 10:51:01)
标签:

杂谈

分类: C#

.........

//

// C9BtnPaint  是继承 button 类的子类;

// 功能实现:添加2排5列button按钮,并为按钮上绘制实心圆点;

窗体部分代码:

 

public Form1()
        {
            InitializeComponent();
            int sX = 40; 
            int sY = 40;
            int btnwidth = 40;
            int pxTime = 0;
            for (int i = 0; i < 2; i++)
            {
                for (int j = 1; j <= 5; j++)
                {
                    pxTime += 1;
                    C9BtnPaint btn = new C9BtnPaint(3 * pxTime);
                    btn.Name = "btn_" + i.ToString() + "_" + j.ToString();
                    this.Controls.Add(btn);
                    btn.SetBounds(sX * (j - 1), sY * i, btnwidth, btnwidth);
                    btn.Click += new EventHandler(btn_Click);
                   
                         
            }
           
        }
        private void btn_Click(object sender, EventArgs e)
        {
            //TODO;

            C9BtnPaint btn = sender as C9BtnPaint;

        }

       

        //  按钮绘制;

        //  窗体1中如果有手动添加的控件,需要对控件组进行判断,再进行绘制;

         private void Form1_Load(object sender, EventArgs e)
        {
            foreach (Control c in this.Controls)
            {
                if (c is C9BtnPaint)
                {
                    C9BtnPaint btn = c as C9BtnPaint;
                    btn.Draw();
                }
            }

 

           // 排列按钮位置;此处跟 2排 5列的按钮无关;仅供参考;

           int btnWidth = 40;
            for (int i = 0; i <= 5;i++ )
            {
                for (int j = 1; j <= 8;j++ )
                {
                    string key = "btn" + i.ToString() + j.ToString();
                    this.Controls[key].Location = new Point(btnWidth *(j-1) , btnWidth* i);
                }
            }
        }

 

 

 

 

 

.........

 

按钮子类C9BtnPaint :

 

 public class C9BtnPaint : Button
       
        public int nPenWidth = 0;
        public C9BtnPaint(int width)
        {
            nPenWidth = width;
            this.FlatStyle = FlatStyle.Standard;
            this.UseVisualStyleBackColor = false;
        }
        public void Draw()
        {
            Bitmap bmp = new Bitmap(40, 40);
            SolidBrush mySolidBrush = new SolidBrush(Color.White);
            Graphics g = Graphics.FromImage(bmp);
            Util.setGraphicsHighQuality(ref g);
            g.FillRectangle(mySolidBrush, 0, 0, 40, 40);
            mySolidBrush.Color = Color.Black;
            g.FillEllipse(mySolidBrush, (40 - nPenWidth) / 2, (40 - nPenWidth) / 2, nPenWidth, nPenWidth);
            mySolidBrush.Dispose();
            g.Dispose();
            this.Image = bmp;
        }
       
    }

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有