-
在Silverlight的登录页面中经常用到输入验证码,怎么生成的呢,其实和.NET生成差不多,以下简单介绍一种:
1、在Silverlight项目下建立一个类IndentifyCodeClass.cs文件
1)、首先注意添加引用 using System.Windows.Media.Imaging;
2)、添加一个用来产生验证码的方法
public String CreateIndentifyCode(int count)
{
String allchar = "1,2,3,4,5,6,7,8,9,A,a,B,b,C,c,D,d,E,e,F,f," +
"G,g,H,h,I,i,J,j,K,k,L,l,M,m,N,n,O,o,P,p,Q,q,R,r,S,s," +
"T,t,U,u,V,v,W,w,X,x,Y,y,Z,z";
String[] allchararray = allchar.Split(',');
String randomcode = "";
int temp = -1;
Random rand = new Random();
for (int i = 0; i < count; i++)
{
if (temp != -1)
{
rand = new Random(i * temp * ((int)datetiR_362_11845@e.Now.Ticks));
}
int t = rand.Next(61);
if (temp == t)
{
return CreateIndentifyCode(count);
}
temp = t;
randomcode += allchararraY[t];
}
return randomcode;
}3)、添加一个方法,用来产生验证码的背景噪声图片
Random r = new Random(datetiR_362_11845@e.Now.Millisecond);
public void CreatImage(String Text,Image imgsource,int iw,int ih)
{
Grid Gx = new Grid();
Canvas cv1 = new Canvas();
for (int i = 0; i < 6; i++)
{
Polyline p = new Polyline();
for (int ix = 0; ix < r.Next(3,6); ix++)
{
p.points.Add(new Point(r.NextDouble() * iw,
r.NextDouble() * ih));
}
byte[] Buffer = new byte[3];
r.NextBytes(Buffer);
SolidColorBrush SC = new SolidColorBrush(Color.FromArgb(255,
Buffer[0],Buffer[1],Buffer[2]));
p.stroke = Sc;
p.strokeThickness = 0.5;
cv1.Children.Add(p);
}
Canvas cv2 = new Canvas();
int y = 0;
int lw = 6;
double w = (iw - lw) / Text.Length;
int h = (int)ih;
foreach (char x in Text)
{
byte[] Buffer = new byte[3];
r.NextBytes(Buffer);
SolidColorBrush SC = new SolidColorBrush(Color.FromArgb(255,Buffer[2]));
TEXTBlock t = new TextBlock();
t.TextAlignment = TextAlignment.Center;
t.FontSize = r.Next(h - 3,h);
t.Foreground = Sc;
t.Text = x.ToString();
t.Projection = new PlaneProjection()
{
RotationX = r.Next(-30,30),
RotationY = r.Next(-30,
RotationZ = r.Next(-10,10)
};
cv2.Children.Add(t);
Canvas.SetLeft(t,lw / 2 + y * w);
Canvas.SetTop(t,0);
y++;
}
Gx.Children.Add(cv1);
Gx.Children.Add(cv2);
WriteableBitmap W = new WriteableBitmap(Gx,new TransformGroup());
W.Render(Gx,new TransformGroup());
imgsource.source = W;
}2、在登录页面的UserControl_Loaded事件中添加如下代码即可:
IndentifyCodeClass code = new IndentifyCodeClass();
String generatedCode = code.CreateIndentifyCode(6);
code.CreatImage(generatedCode,checkCodeImage,150,30);3、获取用户在文本框中输入的验证码,然后和产生的验证码进行比较验证。
....
String indentifyCode = this.tbIndentifyCode.Text.trim();
if(generatedCode !=indentifyCodE)
this.tbIndentifyCode.Focus(); //输入焦点聚焦
}
问题: 3中的generatedCode是局部变量