如何根据WinForms中的切换状态在切换按钮上绘制加号/减号

时间:2015-12-16 06:50:36

标签: winforms togglebutton

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;
        }
    }
}

这是我的代码,我自定义CheckBox并将其外观设置为Button,以便它将作为切换按钮。

我需要绘制一条小的水平线,在Button上显示为负,并绘制一条小的水平和垂直线,显示为加号按钮。因此,它需要切换,如果它处于已检查状态,需要显示,如果未经检查,则需要显示在切换按钮上

先谢谢

1 个答案:

答案 0 :(得分:0)

我会使用imageList控件并分别使用 plus minus 图像填充所需的分辨率。

控件的BackgroundImage属性可用于设置&#34; +&#34;和&#34; - &#34;图像。

并且,不要忘记注册控件的CheckedChanged事件以切换控件的BackgroundImage

例如这样的东西 -

    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];
        }
    }