1
private
bool
_mouseEntered;
2
protected
override
void
OnPaint(PaintEventArgs e)
3
{
4
//
将文本绘制到正中央
5
SizeF stringSize
=
e.Graphics.MeasureString(Text, Font);
6
float
startx
=
(Width
-
stringSize.Width)
/
2
;
7
float
starty
=
(Height
-
stringSize.Height)
/
2
;
8
e.Graphics.DrawString(Text, Font,
new
SolidBrush(ForeColor), startx, starty);
9
base
.OnPaint(e);
10
}
11
protected
override
void
OnPaintBackground(PaintEventArgs pevent)
12
{
13
//
绘制过程为 控件整体背景色->控件有效区背景色->控件状态表示区域->控件外框
14
15
//
**********
16
//
控件整体背景色
17
//
**********
18
if
(
this
.Parent
!=
null
)
19
pevent.Graphics.FillRectangle(
new
SolidBrush(Parent.BackColor),
0
,
0
,
this
.Width,
this
.Height);
20
//
使用高质量平滑模式消除椭圆边缘锯齿
21
pevent.Graphics.SmoothingMode
=
SmoothingMode.HighQuality;
22
23
//
***********
24
//
控件有效区背景色
25
//
************** Control.MouseButtons静态成员
26
if
(_mouseEntered
&&
(MouseButtons
&
MouseButtons.Left)
==
MouseButtons.Left)
27
{
28
Color mouseDownColor
=
Color.FromArgb(
128
, BackColor);
29
pevent.Graphics.FillEllipse(
new
SolidBrush(mouseDownColor),
0
,
0
, Width
-
1
, Height
-
1
);
30
}
31
else
32
pevent.Graphics.FillEllipse(
new
SolidBrush(BackColor),
0
,
0
, Width
-
1
, Height
-
1
);
33
34
//
***********
35
//
控件状态表示区域
36
//
************
37
//
左键未按下时绘制状态表示区域
38
if
((MouseButtons
&
MouseButtons.Left)
!=
MouseButtons.Left)
39
{
40
//
鼠标进入 绘制橙色边框
41
if
(_mouseEntered)
42
{
43
Pen mouseEnterPen
=
new
Pen(Color.Orange,
2
);
44
pevent.Graphics.DrawEllipse(mouseEnterPen,
1
,
1
, Width
-
3
, Height
-
3
);
45
mouseEnterPen.Dispose();
46
}
47
//
控件获得焦点 但鼠标未进入 绘制蓝色边框
48
else
if
(Focused)
49
{
50
Pen focusedPen
=
new
Pen(Color.PowderBlue,
2
);
51
pevent.Graphics.DrawEllipse(focusedPen,
1
,
1
, Width
-
3
, Height
-
3
);
52
focusedPen.Dispose();
53
}
54
}
55
//
如果有焦点,绘制焦点框
56
if
(Focused)
57
{
58
Pen focusedDotPen
=
new
Pen(Color.Black);
59
focusedDotPen.DashStyle
=
DashStyle.Dot;
60
pevent.Graphics.DrawEllipse(focusedDotPen,
3
,
3
, Width
-
7
, Height
-
7
);
61
focusedDotPen.Dispose();
62
}
63
64
//
*********
65
//
控件外框
66
//
**********
67
pevent.Graphics.DrawEllipse(Pens.Black,
0
,
0
, Width
-
1
, Height
-
1
);
68
69
//
base.OnPaintBackground(pevent);
70
}