ASP.net 验证码(C#)[1]

[入库:2005年8月18日] [更新:2007年3月27日]

本文简介:选择自 hanghwp 的 blog

/* copyright all(c) 2005 zhongfeng, http://blog.csdn.net/sw515 */
 public class validatecode : system.web.ui.page
 {
  private void page_load(object sender, system.eventargs e)
  {
   this.createcheckcodeimage(generatecheckcode());
  }

  #region web 窗体设计器生成的代码
  override protected void oninit(eventargs e)
  {
   //
   // codegen: 该调用是 asp.net web 窗体设计器所必需的。
   //

   initializecomponent();
   base.oninit(e);
  }
  
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>

  private void initializecomponent()
  {   
   this.load += new system.eventhandler(this.page_load);
  }
  #endregion

  private string generatecheckcode()
  {
   int number;
   char code;
   string checkcode = string.empty;

   system.random random = new random();

   for(int i=0; i<5; i++)
   {
    number = random.next();

    if(number % 2 == 0)
     code = (char)('0;& + (char)(number % 10));
    else
     code = (char)(&a& + (char)(number % 26));

    checkcode += code.tostring();
   }

   response.cookies.add(new httpcookie("checkcode", checkcode));

   return checkcode;
  }

  private void createcheckcodeimage(string checkcode)
  {
   if(checkcode == null || checkcode.trim() == string.empty)
    return;

   system.drawing.bitmap image = new system.drawing.bitmap((int)math.ceiling((checkcode.length * 12.5)), 22);
   graphics g = graphics.fromimage(image);

   try
   {
    //生成随机生成器
    random random = new random();

    //清空图片背景色
    g.clear(color.white);

    //画图片的背景噪音线
    for(int i=0; i<25; i++)
    {
     int x1 = random.next(image.width);
     int x2 = random.next(image.width);
     int y1 = random.next(image.height);
     int y2 = random.next(image.height);

     g.drawline(new pen(color.silver), x1, y1, x2, y2);

本文关键:,ASP.net 验证码(C#),
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top