Search code examples
winformstogglebutton

How to draw a Plus/Minus on a Toggle Button based on Toggle State in WinForms


public partial class Form1 : Form
{
    CheckBoxExt checkBox;
    public Form1()
    {
        InitializeComponent();
        checkBox = new CheckBoxExt();
        this.Controls.Add(checkBox);
    }
}
public class CheckBoxExt : CheckBox
{
    public CheckBoxExt()
    {
        this.Size = new Size(20, 20);
        this.Location = new Point(200, 200);
        this.Appearance = Appearance.Button;
    }
    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        var point = this.PointToScreen(new Point(0, 0));
        e.Graphics.DrawLine(new Pen(ColorTranslator.FromHtml("#666666"), 2), new Point(point.X + 5, point.Y + 10), new Point(point.X + 15, point.Y + 10));
        if (this.Checked)
            e.Graphics.DrawLine(new Pen(ColorTranslator.FromHtml("#666666"), 2), new Point(point.X + 10, point.Y + 5), new Point(point.X + 10, point.Y + 15));
    }
    /// <summary>
    /// to remove the focus dotted border over the control
    /// </summary>
    protected override bool ShowFocusCues
    {
        get
        {
            return false;
        }
    }
}

Here is my code, i customized CheckBox and sets it Appearance as Button so that it will act as Toggle button.

i need to draw a small horizontal line which will display as minus on the Button, and draw a small horizontal and vertical line which will display as Plus button. Hence it need to toggled, if it's in checked state plus need to be shown and if it's unchecked minus need to be shown over the toggle button

Thanks in Advance


Solution

  • I would use an imageList control and populated it with plus and minus images respectively with desired resolution.

    The BackgroundImage property of the control can be used to set "+" and "-" images.

    And, don't forget to register CheckedChanged event of the control to toggle the BackgroundImage of the control.

    Something like this for example -

        public Form1()
        {
            InitializeComponent();
    
            var checkBox = new CheckBoxExt();
    
            //My imageList contain two images, for "+" and "-"
    
            //Register chacked changed event for the control
            checkBox.CheckedChanged += checkBox_CheckedChanged;
    
            //Set the initial image as "-"
            checkBox.BackgroundImage = this.imageList1.Images[1];
    
            this.Controls.Add(checkBox);
        }
    
        void checkBox_CheckedChanged(object sender, EventArgs e)
        {
            if (((CheckBox)sender).Checked)
            {
                ((CheckBox)sender).BackgroundImage = this.imageList1.Images[0];
            }
            else
            {
                ((CheckBox)sender).BackgroundImage = this.imageList1.Images[1];
            }
        }