using System; using System.Web.UI; using System.Web.UI.WebControls; using System.ComponentModel; using System.IO; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging;
//[ToolboxBitmap(@"D:\DotnetApp\ValidateCode\ValidateCode.bmp") ] //设置控件在工具箱上的图标 public class ValidateCode : System.Web.UI.WebControls.WebControl ,INamingContainer { private int pCodelen=5; private int pChartWidth=100; private int pChartHeight=20;
//生成校验码的变量 start private Bitmap validateImage; private Graphics g; //生成校验码的变量 End
private TextBox txt=new TextBox(); private System.Web.UI.WebControls.Image img= new System.Web.UI.WebControls.Image();
#region 定义控件事件
public delegate void GraphicCreated(object sender, EventArgs e); public event EventHandler GraphicOK; //在校验图片生成结束以后触发
protected virtual void OnGraphicOK(object sender, EventArgs e) { if (GraphicOK != null) { //Invokes the delegates. GraphicOK(sender, e); } }
#endregion
#region 控件属性
//生成校验码的长度 [Bindable(true),Browsable(true),Category("Appearance"),DefaultValue(true),Description("需要验证码的长度,建议在5~8位之间!")] public int CodeLength { get { return pCodelen; }
set { pCodelen = value; } }
//生成校验码的长度 [Bindable(true),Browsable(true),Category("Appearance"),DefaultValue(true),Description("生成验证码图片的临时存放路径,要求必须是网站下的虚拟目录!")] public string TempImageURLPath { get { return pTempImageURLPath; }
set { pTempImageURLPath = value; } }
[Bindable(true),Browsable(true),Category("Appearance"),DefaultValue(GraphicType.Jpg),Description("选择生成校验图文件的类型(Jpg;Gif;Png;Bmp)!")] public GraphicType ChartType { get { return pChartType; }
set { pChartType = value; } }
//生成校验码图片的宽度 public int ChartWidth { get { return pChartWidth; }
set { pChartWidth = value; } }
//生成校验码图片的高度 public int ChartHeight { get { return pChartHeight; }
set { pChartHeight = value; } }
//需要生成的校验码 public string AuthenCode { get { return pAuthenCode; }
validateImage = new Bitmap(pChartWidth, pChartHeight, PixelFormat.Format24bppRgb); // .Format24bppRgb); g = Graphics.FromImage(validateImage);
g.Clear(Color.LightGray) ;
//g.DrawString(strValidateCode , new Font("宋体",16,FontStyle.Bold),new SolidBrush(Color.DarkRed),new PointF(2,2));
for(int i=0;i<strValidateCode.Length;i++) { Random r = new Random(); PointF startPos=new PointF(r.Next(3,6)+(r.Next(12,14)*i ),r.Next(-1,2) );
g.DrawString(strValidateCode.Substring(i,1) , new Font("宋体",14,FontStyle.Italic),new SolidBrush(Color.Blue),startPos); }
//g.FillRectangle(new LinearGradientBrush(new Point(0,0), new Point(120,30), Color.FromArgb(0,0,0,0),Color.FromArgb(255,255,255,255)),0,0,120,30); switch(pChartType) { case GraphicType.Jpg: