CheckBox的方框大小是以Hard Coded方式寫死的,因此沒辦法藉由設定CheckBox任何參數來改變勾選框框的大小,但可以透過override方是依自己需求重新繪製方框,直接看程式碼:
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
44
45
46
47
48
| class CheckBoxEx : CheckBox
{
public CheckBoxEx()
{
}
public override string Text
{
get
{
return base.Text;
}
set
{
base.Text = value;
Size size = TextRenderer.MeasureText(value, Font);
if (Width < size.Width + ClientSize.Height)
Width = size.Width + ClientSize.Height;
}
}
public override Font Font
{
get
{
return base.Font;
}
set
{
base.Font = value;
Size size = TextRenderer.MeasureText(Text, value);
if (Width < size.Width + ClientSize.Height)
Width = size.Width + ClientSize.Height;
}
}
protected override void OnPaint(PaintEventArgs e)
{
int h = ClientSize.Height;
Rectangle rc = new Rectangle(new Point(0, 0), new Size(h, h));
e.Graphics.Clear(Parent.BackColor);
ControlPaint.DrawCheckBox(e.Graphics, rc,
this.Checked ? ButtonState.Checked : ButtonState.Normal);
SizeF size = e.Graphics.MeasureString(Text, Font);
e.Graphics.DrawString(Text, this.Font,
new SolidBrush(Color.Blue), new PointF(h, size.Height < h ? (h - size.Height) / 2 : 0));
}
}
|
重點在於重載
OnPaint這個繪圖函數,在函數內使用
ControlPaint.DrawCheckBox重新繪製方框外形,因重載了原本OnPaint,因此要自己把文字補畫上去(參考44 ~ 46行)。
因重設字型大小或顯示文字內容會影響CheckBox的呈現寬度,因此一併重載
Text與
Font屬性,當使用者更改這兩個屬性值,則要重新計算CheckBox的寬度,否則文字呈現可能會被截斷。
使用方法跟一般CheckBox一樣:
1
2
3
4
5
6
| CheckBoxEx check = new CheckBoxEx();
check.Location = new Point(40, 40);
check.ClientSize = new Size(30, 30);
check.Text = "Hello CheckBox";
check.Font = new System.Drawing.Font("新細明體", 18);
Controls.Add(check);
|
Keyword:Customize checkbox size