C# Winform 更改radioButton颜色

自定义一个控件,继承RadioButton类,重写OnPaint方法,参考代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
 public class ColoredRadioButton : RadioButton
{

public ColoredRadioButton()
{
// Allows for Overlaying
SetStyle(
ControlStyles.UserPaint //控件自行绘制,而不使用操作系统的绘制
ControlStyles.AllPaintingInWmPaint //忽略擦出的消息,减少闪烁。
ControlStyles.OptimizedDoubleBuffer //在缓冲区上绘制,不直接绘制到屏幕上,减少闪烁。
ControlStyles.ResizeRedraw //控件大小发生变化时,重绘。
ControlStyles.SupportsTransparentBackColor, true);
BackColor = Color.Transparent;
}
protected override void OnPaint(PaintEventArgs e)
{
m_circle = new Rectangle(7, 9, 8, 8 /*Magic Numbers*/);
m_outlinerect = new Rectangle(4, 6, 14, 14);
m_outline = new Pen(new SolidBrush(Color.FromArgb(0,163,235)), 1.5F /*Magic Numbers*/);

// Init
//base.OnPaint(e);
Graphics g = e.Graphics;

g.Clear(Color.White);
using (SolidBrush brush = new SolidBrush(ForeColor))
g.DrawString(Text, Font, brush, 27, 4);

g.SmoothingMode = SmoothingMode.AntiAlias;

// Overlay Graphic
if (Checked)
{
g.FillEllipse(new SolidBrush(Color.FromArgb(0, 163, 235)), m_circle);
g.DrawEllipse(m_outline, m_outlinerect);
}
else
{
g.FillEllipse(new SolidBrush(Color.White), m_circle);
g.DrawEllipse(m_outline, m_outlinerect);
}
}
}