VS怎么自定义一个控件,这里记录一个简单的小例子。例子自定了PictureBox这个控件,将其形状改写成椭圆。
首先讲讲如何自定义一个控件:
1、创建一个windows窗体空间库的项目
2、项目输出类型改为类库,编译生成,将生成的dll文件复制到特定文件夹
3、在winform项目工具箱里添加dll,即可看到自定义的控件
自定义PictureBox代码:
namespace NChat.App_Code
{
class MyPictureBox : PictureBox
{
public MyPictureBox()
{
this.Width = 70;
this.Height = 35;
}
private Color backcolor;
public new Color BackColor
{
get { return this.backcolor; }
set { this.backcolor = value; }
}
protected override void OnCreateControl()
{
//this.Height = 35;
//this.Width = 70;
//Rectangle rec = new Rectangle(0, 0, this.Width, this.Height);
//GraphicsPath gp = new GraphicsPath();
//gp.AddEllipse(rec);
//// gp.AddEllipse(this.ClientRectangle);
//Region region = new Region(gp);
//this.Region = region;
//gp.Dispose();
//region.Dispose();
//base.OnCreateControl();
}
protected override void OnPaint(PaintEventArgs pe)
{
Color color = Color.Orange;
Rectangle rec = new Rectangle(0, 0, this.Width, this.Height);
Brush b = new SolidBrush(Color.SkyBlue);//声明的画刷
//Brush b = new LinearGradientBrush(new Point(0, this.Width / 2), new Point(this.Height, this.Width / 2), color, color);//LinearGradientBrush是要System.Drawing.Drawing2D;命名控件下的,可以是填充颜色渐变
Graphics g = pe.Graphics;
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.NearestNeighbor;
g.CompositingQuality = CompositingQuality.HighQuality;
g.DrawEllipse(Pens.Black, rec);
g.FillEllipse(b, rec);
this.backcolor = Color.SkyBlue;
base.OnPaint(pe);
}
public void OnPaint(PaintEventArgs pe,Color color)
{
Rectangle rec = new Rectangle(0, 0, this.Width, this.Height);
Brush b = new SolidBrush(color);//声明的画刷
//Brush b = new LinearGradientBrush(new Point(0, this.Width / 2), new Point(this.Height, this.Width / 2), color, color);//LinearGradientBrush是要System.Drawing.Drawing2D;命名控件下的,可以是填充颜色渐变
Graphics g = pe.Graphics;
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.NearestNeighbor;
g.CompositingQuality = CompositingQuality.HighQuality;
g.DrawEllipse(Pens.Black, rec);
g.FillEllipse(b, rec);
this.backcolor = color;
base.OnPaint(pe);
}
protected override void OnSizeModeChanged(EventArgs e)
{
base.OnSizeModeChanged(e);
this.OnCreateControl();
}
}
}
namespace WindowsFormsControlLibrary1
{
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
public new Color BackColor
{
get { return myPictureBox1.BackColor; }
set
{
Rectangle rec = new Rectangle(0, 0, myPictureBox1.Width, myPictureBox1.Height);
//Graphics g = new Graphics();
PaintEventArgs pe = new PaintEventArgs(myPictureBox1.CreateGraphics(), rec);
myPictureBox1.OnPaint(pe, value);
}
}
}
}