日期:2014-05-17  浏览次数:21060 次

C# 生成随机验证码的问题?
C# code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace RandomCode
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private Random rd;
        private int gg;

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            Graphics gh = e.Graphics;
            rd = new Random();
            gg = rd.Next(1000, 10000);
            Font font = new Font(FontFamily.Families[5], 10);
            SolidBrush brush = new SolidBrush(Color.SandyBrown);
            gh.DrawString(gg.ToString(),font,brush, 0, 0);
        }

        private void Draw_Click(object sender, EventArgs e)
        {
            Rectangle rc = new Rectangle(0,0,40,20);
            this.Invalidate(rc);
        }

        private void Check_Click(object sender, EventArgs e)
        {
            try
            {

                if (gg != Convert.ToInt32(message.Text.Trim()))
                {
                    MessageBox.Show("请输入正确的验证码");
                }
            }
            catch (FormatException exp)
            {
                MessageBox.Show(exp.Message);
            }
        }
    }
}

大家帮忙看看,try语句执行的效果,输入正确(按程序界面上显示的数据来看)的数字也会弹出错误,也不太好调试,
我想问题多半出在override这个语句上,没有搞清楚它的执行原理
怎样正确的验证,那位能不吝指教下?
谢谢为先

------解决方案--------------------
为什么不自己写一个方法呢?我自己弄了一个简单的
namespace ChinaRecipe
{
class CValidate
{
public string rndnum()
{
int j1;
string strChoice = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,w,x,y,z";
string[] strResulu = strChoice.Split(new Char[] { ',' });
string strReturn = "";
Random rnd = new Random(unchecked((int)DateTime.Now.Ticks));
for (int i = 0; i < 6; i++)
{
Random rnd1 = new Random(rnd.Next() * unchecked((int)DateTime.Now.Ticks));
j1 = rnd1.Next(35);
rnd1 = new Random(rnd1.Next() * unchecked((int)DateTime.Now.Ticks));
strReturn = strReturn + strResulu[j1].ToString();
}
return strReturn;

}
public Bitmap ValidateCode(string vnum)
{
MemoryStream ms = new MemoryStream();
double Height = (vnum.Length) * 30;
int gHeight = Convert.ToInt32(Height);
Bitmap img = new Bitmap(gHeight, 30);
Graphics g = Graphics.FromImage(img);
g.DrawString(vnum, (new Font("幼圆", 13)), (new SolidBrush(Color.Blue)), 1, 4);
img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
return img;

}
}
}


你在调用的窗口中:

 CValidate cv = new CValidate();
string cvString = cv.rndnum();
Bitmap cvbmp = cv.ValidateCode(cvString);
pbValidate.Image = cvbmp;


然后验证就行了

------解决方案--------------------


3楼的方法一起研究研究!