1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Threading.Tasks; 9 using System.Windows.Forms; 10 11 namespace WindowsFormsApplication2 12 { 13 public partial class Form1 : Form 14 { 15 public Form1() 16 { 17 InitializeComponent(); 18 } 19 private void Form1_Load(object sender, EventArgs e) 20 { 21 string vc = ""; 22 Random rNum = new Random();//随机生成类 23 int num1 = rNum.Next(0, 9);//返回指定范围内的随机数 24 int num2 = rNum.Next(0, 9); 25 int num3 = rNum.Next(0, 9); 26 int num4 = rNum.Next(0, 9); 27 28 int[] nums = new int[4] { num1, num2, num3, num4 }; 29 for (int i = 0; i < nums.Length; i++)//循环添加四个随机生成数 30 { 31 vc += nums[i].ToString(); 32 } 33 lblVerificationCode.Text = vc; 34 } 35 private void btnVerification_Click(object sender, EventArgs e) 36 { 37 if (txtInput.Text != null && txtInput.Text != "")//用户输入不为空 38 { 39 if (txtInput.Text == lblVerificationCode.Text)//判断用户输入与随机生成的四位数是否相同 40 { 41 MessageBox.Show("验证成功!"); 42 } 43 else 44 { 45 MessageBox.Show("验证失败!"); 46 } 47 } 48 else 49 { 50 MessageBox.Show("请输入验证码!"); 51 } 52 } 53 54 55 } 56 }
原文:http://www.cnblogs.com/liupingii/p/7113387.html