<分区>
我想更改边框颜色和正方形的背景以及复选标记的颜色,但不更改文本。为了更好地理解,我想完成的是以下示例:
checkBox1.Checked = false
checkBox1.Checked = true
非常感谢大家对这个请求的准确回应!
<分区>
我想更改边框颜色和正方形的背景以及复选标记的颜色,但不更改文本。为了更好地理解,我想完成的是以下示例:
checkBox1.Checked = false
checkBox1.Checked = true
非常感谢大家对这个请求的准确回应!
最佳答案
您可以简单地在 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);
}
要实现这一点,您需要:
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);
}
}
您可能需要调整控件和字体的大小。如果您想扩展代码以支持 TextAlign
和 CheckAlign
属性。
如果您需要一个三态控件,您可以调整代码以显示第三种状态外观,尤其是当您想到一个看起来比原始外观更好的控件时。
关于c# - 如何更改 CheckBox 复选标记的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35252382/