下面我们就开始简单的例子来介绍这个过程,首先打开VS.NET,新建一个Web Site,添加一个新的 Web Form,取名为 VCode.aspx,在其代码文件(VCode.aspx.vb)中添加一个函数generateVCode,此函数用于生成校验码的字符串,具体代码如下:
''' <summary>
''' 产生随机数(包含字母与数字)用于校验码
''' </summary>
''' <param name="CodeLength"></param>
''' <returns></returns>
''' <remarks></remarks>
Private Function generateVCode(ByVal CodeLength As Integer) As String
Dim VCode As String = String.Empty
Dim randObj As New Random()
Dim c As Integer = 63
For i As Byte = 1 To CodeLength
c = randObj.Next(35)
If c >= 10 Then
c += 7
End If
c += 48
VCode += Chr(c)
Next
Return VCode
End Function
''' <summary>
''' 产生随机的笔触样式(用于图像的背景)
''' </summary>
''' <returns></returns>
''' <remarks></remarks>
Private Function generateHatchStyle() As HatchStyle
Dim slist As New ArrayList
For Each style As HatchStyle In System.Enum.GetValues(GetType(HatchStyle))
slist.Add(style)
Next
Dim randObj As New Random()
Dim index As Integer = randObj.Next(slist.Count - 1)
Return CType(slist(index), HatchStyle)
End Function
Dim oBitmap As Bitmap = New Bitmap(90, 35)
Dim oGraphic As Graphics = Graphics.FromImage(oBitmap)
Dim foreColor As System.Drawing.Color
Dim backColor As System.Drawing.Color
Dim sText As String = generateVCode(5) '获取校验码字符串
Dim sFont As String = "Comic Sans MS" '设置自己喜欢的字体
'设置用于背景的画笔
Dim oBrush As New HatchBrush(CType(generateHatchStyle(), HatchStyle), foreColor, backColor)
'用于输出校验码的画笔
Dim oBrushWrite As New SolidBrush(Color.Gray)
Return sText
End Function
上面介绍的都是几个实现具体功能的函数,我们还需要在VCode.aspx的Page Load事件里面添加调用这些函数的代码,具体如下:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim code As String = GenerateVCodeImage()
Session("VCode") = code
End Sub
Protected Sub btnCheck_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCheck.Click
Dim code As String = Session("VCODE")
If TextBox1.Text.Trim.ToUpper = code Then
lblMessage.Text = "校验成功!"
lblMessage.ForeColor = Color.Blue
Else
lblMessage.Text = "您输入的注册码错误!"
lblMessage.ForeColor = Color.Red
End If
TextBox1.Text = ""
End Sub
具体的效果如下:
Private Function generateVCode(ByVal CodeLength As Integer) As String
Dim VCode As String = String.Empty
Dim randObj As New Random()
Dim c As Integer = 63
For i As Byte = 1 To CodeLength
'是否显示 数字:0, 因为数字0 与字母O 容易混淆
'While (c = 63)
' c = randObj.Next(35)
'End While
c = randObj.Next(35)
If c >= 10 Then
c += 7
End If
c += 48
VCode += Chr(c)
Next