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

use*_*584 6 c# winforms

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

  • checkBox1.Checked = false

  • checkBox1.Checked = true

非常感谢大家的回应!

TaW*_*TaW 12

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

在此输入图像描述

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);
}
Run Code Online (Sandbox Code Playgroud)

为此,您需要:

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

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

在此输入图像描述

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

  • 我已经修改了该类以包含焦点矩形并完成所有文本绘制。 (2认同)