How to change checkbox flag color?

I want to change the border color and the background of the square and the color of the checkmark, but not the text. To better understand what I want to do, the following example:

  • checkBox1.Checked = false

  • checkBox1.Checked = true

Thank you, each of you answers exactly this request!

+5
source share
2 answers

You can simply draw a check mark in the Paint event:

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

for this you need:

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

If you want to reuse this, it is best to subclass this flag and override the OnPaint event. Here is an example:

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

You may need to resize the control and font. And if you want to extend the code to read the TextAlign and CheckAlign .

And if you need a control with three states, you can adapt the code to display the third state, especially if you think about what looks better than the original.

+9
source

You need to write your own checkbox. Having created your own control, in which there is a blue square (possibly inherited from Button), which switches between marked and unverified images by the OnClick event and places a shortcut next to it.

+3
source

Source: https://habr.com/ru/post/1242475/


All Articles