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

标签 c# winforms

<分区>

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

  • checkBox1.Checked = false

  • checkBox1.Checked = true

非常感谢大家对这个请求的准确回应!

最佳答案

您可以简单地在 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 属性。

如果您需要一个三态控件,您可以调整代码以显示第三种状态外观,尤其是当您想到一个看起来比原始外观更好的控件时。

关于c# - 如何更改 CheckBox 复选标记的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35252382/

相关文章:

c# - 有没有办法在递归调用之前检查可用的堆栈大小? (C#)

c# - 匹配大型文本数据集——如何更快地匹配?

c# - 如何访问azure webrole中的signalr hub

c# - ASP :CreateUserWizard Redirecting After Complete

c# - 尝试检索插入预订表的最后一个 ID,但收到 "Subquery returns more than 1 row"错误消息

c# - MEF 加载和卸载特定插件?

c# - 公共(public)类和方法会降低您的代码速度吗?

c# - 如何更改菜单悬停颜色

winforms - 如何 : Paint a dotted line in . NET (WinForms)

C# control.find 解释