954,505 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?

Custom checkbox

0
By Marivoet Daniel on Apr 26th, 2009 11:32 pm

I wanted to make an array of bits which I could click on and off at will. Sort of a register you could manipulate. First thing that came up was a checkbox control. But I wanted to change the usual checkmark with a 1 or a 0. With tips from JerryShaw and Ramy Marhous I came up with the following.

public partial class Form1 : Form
    {
        private BinarycheckBox BinCB;
            
        public Form1()
        {
            InitializeComponent();

            //initialize new binary checkbox
            BinCB = new BinarycheckBox();
           
            BinCB.AutoSize = true;
            BinCB.Location = new System.Drawing.Point(70, 95);
            BinCB.Name = "bin";
            BinCB.Size = new System.Drawing.Size(25, 17);
            BinCB.TabIndex = 0;
            BinCB.Text = "bla bla";
            BinCB.UseVisualStyleBackColor = true;
            this.Controls.Add(BinCB);          
        }
    }

  class BinarycheckBox : CheckBox
        //class derived from the CheckBox class
    {
        //init vars for OnPaint
        private Font font = new Font("Ariel", 8);
        private static Brush bluebrush = new SolidBrush(Color.Blue);
        private Brush backgroundbrush = new SolidBrush(Color.Yellow);
        Pen bluepen = new Pen(bluebrush);  
        private StringFormat strFormat = new StringFormat();

        //default constructor
        public BinarycheckBox(){}

        //we only need to override the OnPaint method 
        //we do our own painting here
        protected override void OnPaint(PaintEventArgs pevent)
        {
            base.OnPaint(pevent);   //needed
            base.FlatStyle = FlatStyle.Flat; //needed

            Graphics G = pevent.Graphics;
            strFormat.Alignment = StringAlignment.Center;
            strFormat.LineAlignment = StringAlignment.Center;

            RectangleF R = new RectangleF(G.ClipBounds.X, G.ClipBounds.Y, 16F, 16F);

            G.FillRectangle(backgroundbrush, R);
            if (this.Checked)
                G.DrawString("1", font, bluebrush, R, strFormat);
            else
                G.DrawString("0", font, bluebrush, R, strFormat);
        
            G.DrawRectangle(bluepen, R.X, R.Y, R.Width - 1, R.Height - 1);          
        }
    }

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: