基于c#的自制控件:Button
摘 要:
关键词:c#;button;usercontrol
一、概述:
有时Visual Studio提供的控件不能满足用户的需求,此时我们可以去购买第三方控件,但是一些简单的控件我们完全可以自己制作出来,接下来,我们将自己动手制作一个圆形的button控件,它实现了button控件所需要具有的几乎全部特性。Control是定义控件的基类,控件是带有可视化表示形式的组件。所以我们让RoundButton继承自Control,且实现IButtonControl接口,IButtonControl接口将允许控件在窗体上的作用就像按钮一样。类关系图如图1-1所示。
图1-1 图1-2 图1-3 图1-4
代码实现:
1. 字段的设置
public class RoundButton : Control, IButtonControl
{
private ButtonState myButtonState;
private DialogResult myDialogResult;
private bool IsDefault { get; set; }
//...other method
}
2. Button外观的的绘制
protected override void OnPaint(PaintEventArgs e)
{
t(e);
PaintStandart(cs);
}
private void PaintStandart(Graphics g)
{
ingMode = ias;//指定消除锯齿的呈现。
Rectangle rect = new Rectangle(2, 2, - 4, - 4);
if (d)
{
e(-2, -2);
DrawFocus(g);
}
PaintButtonBackGround();
Draw3DBorder(rect, g);
DrawText(rect, g);
}
private void PaintButtonBackGround()
{
GraphicsPath myPath = new GraphicsPath();
ipse(0, 0, , );
Region myRegion = new Region(myPath);
= myRegion;
}
private void Draw3DBorderPushed(Rectangle rect, Graphics g)
{
using (Pen myPen = new Pen(lDarkDark, 3))
{
lipse(myPen, rect);
}
}
private void Draw3DBorder(Rectangle rect, Graphics g)
{
if (myButtonState == )
Draw3DBorderPushed(rect, g);
else
Draw3DBorderNormal(rect, g);
}
private void Draw3DBorderNormal(Rectangle rect, Graphics g)
{
LinearGradientBrush myBrush =
new LinearGradientBrush(rect, , ,
dDiagonal);
using (Pen myPen = new Pen(myBrush, 3))
{
lipse(myPen, rect);
}
}
private void DrawFocus(Graphics g)
{
Rectangle myRect =
new Rectangle(1, 1, - 2, - 2);
using (Pen myPen = new Pen())
{
lipse(myPen, myRect);
}
}
private void DrawText(Rectangle rect, Graphics g)
{
StringFormat myFormat = new StringFormat();
ent = ;
ignment = ;
if (d)
{
(1, 1);
ring(, ,
new SolidBrush(lor), rect, myFormat);
}
else
{
(1, 1);
ring(, ,
new SolidBrush(), rect, myFormat);
(-1, -1);
ring(, ,
new SolidBrush(xt), rect, myFormat);
}
}
3. IButtonControl接口的实现
[Category(""Behavior""), DefaultValue()]
public virtual DialogResult DialogResult
{
get{ return myDialogResult;}
set{myDialogResult = value;}
}
public void NotifyDefault(bool value)
{
if (ult != value)
ult = value;
if (ult == true) ();
else
Focus();
}
public void PerformClick()
{
if (ect)
k();
}
protected override void OnClick(EventArgs e)
{
k(e);
((Form)elControl).DialogResult = myDialogResult;
}
二、总结:
本文通过一个简单的例子起到抛砖引玉的作用,依照这些步骤,大家完全可以制作出属于自己的更有个性的button。用户界面由各种控件组成,应用自制的控件将会使用户界面更为丰富,使他人眼前一亮。