如何更改CheckBox复选标记的颜色?

时间:2016-02-07 10:37:26

标签: c# winforms

我想更改边框颜色和方块的背景以及复选标记的颜色,但不更改文本。为了更好地理解,我想要完成的是以下示例:

  • checkBox1.Checked = false

  • checkBox1.Checked = true

非常感谢大家对此请求的回应!

2 个答案:

答案 0 :(得分:12)

您只需在Paint事件中绘制复选标记:

enter image description here

private void checkBox1_Paint(object sender, PaintEventArgs e)
{
    Point pt = new  Point(e.ClipRectangle.Left + 2, e.ClipRectangle.Top + 4);
    Rectangle rect = new Rectangle(pt, new Size(22, 22));
    if (checkBox1.Checked)
    {
       using (Font wing = new Font("Wingdings", 14f))
          e.Graphics.DrawString("ü", wing, Brushes.DarkOrange,rect);
    }
    e.Graphics.DrawRectangle(Pens.DarkSlateBlue, rect);
}

为此,您需要:

  • 设置Apperance = Appearance.Button
  • 设置FlatStyle = FlatStyle.Flat
  • 设置TextAlign = ContentAlignment.MiddleRight
  • 设置FlatAppearance.BorderSize = 0
  • 设置AutoSize = false

如果要重新使用它,最好将复选框子类化并覆盖OnPaint事件。这是一个例子:

enter image description here

public ColorCheckBox()
{
    Appearance = System.Windows.Forms.Appearance.Button;
    FlatStyle = System.Windows.Forms.FlatStyle.Flat;
    TextAlign = ContentAlignment.MiddleRight;
    FlatAppearance.BorderSize = 0;
    AutoSize = false;
    Height = 16;
}

protected override void OnPaint(PaintEventArgs pevent)
{
    //base.OnPaint(pevent);

    pevent.Graphics.Clear(BackColor);

    using (SolidBrush brush = new SolidBrush(ForeColor))
        pevent.Graphics.DrawString(Text, Font, brush, 27, 4);

    Point pt = new Point( 4 ,  4);
    Rectangle rect = new Rectangle(pt, new Size(16, 16));

    pevent.Graphics.FillRectangle(Brushes.Beige, rect);

    if (Checked)
    {
        using (SolidBrush brush = new SolidBrush(ccol))
        using (Font wing = new Font("Wingdings", 12f))
            pevent.Graphics.DrawString("ü", wing, brush, 1,2);
    }
    pevent.Graphics.DrawRectangle(Pens.DarkSlateBlue, rect);

    Rectangle fRect = ClientRectangle;

    if (Focused)
    {
        fRect.Inflate(-1, -1);
        using (Pen pen = new Pen(Brushes.Gray) { DashStyle = DashStyle.Dot })
            pevent.Graphics.DrawRectangle(pen, fRect);
    }
}

您可能需要调整控件和字体的大小..如果您想扩展代码以尊重TextAlignCheckAlign属性。

如果你需要一个三态控件,你可以调整代码以显示第三个状态外观,特别是如果你想到一个看起来比原来更好的那个......

答案 1 :(得分:3)

您必须编写自己的复选框。通过制作一个自定义控件,其中有一个蓝色正方形(可能从Button继承),通过OnClick事件在已检查和未检查的图像之间切换,并在其旁边放置一个标签。