using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace chx01
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void btnView_Click(object sender, EventArgs e)
{
//15位身份证:省(2)市(2)区[县](2)年(2)月(2)日(2)+3序列号[奇数分配给男性/偶数分配给女性]
//15位升级为18位:第一点:出生年前面都加上19 第二点:第18位叫做校验位,也就是说第18位要从前17位计算而来
//身份证目前可能会见到15位和18位两种
//如果是15位身份证,那么我们取第7、8位就是出生年
//如果是18位身份证,先校验用户输入的身份证是否合法,如果合法再取7-10位,就是出生年
int age = 0;
int year = 0;
string id = txtId.Text.Trim();
if(id.Length == 15)
{
year = Convert.ToInt32(id.Substring(6, 2)) + 1900;
}
else if(id.Length == 18)
{
if(!this.CheckCardId(id))
{
MessageBox.Show("身份证号码输入有误,请检查!");
return;
}
year = Convert.ToInt32(id.Substring(6, 4));
}
else
{
MessageBox.Show("身份证号码长度输入有误!");
}
age = DateTime.Now.Year - year;
if (age >= 18)
{
pic.Visible = true;
}
else
{
MessageBox.Show("你太小了,回家看动画片吧!");
}
}
//校验身份证号,如果正确则返回true,否则返回false
private bool CheckCardId(string id)
{
int[] wQuan = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
string checkWei = "10X98765432";
string number17 = id.Substring(0, 17);
string number18 = id.Substring(17);
int sum = 0;
for(int i = 0;i < 17; i++)
{
sum = sum + Convert.ToInt32(number17[i].ToString()) * wQuan[i];
}
int mod = sum % 11;
string result = checkWei[mod].ToString();
if(number18.Equals(result, StringComparison.OrdinalIgnoreCase))
{
return true;
}
else
{
return false;
}
}
private void txtId_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar < '0' || e.KeyChar > '9')
{//输入数字以外的字符就阻止掉
e.Handled = true;
}
//如果第18位输入的字符是x,则不阻止
if((txtId.SelectionStart == 17) && (e.KeyChar == 'x' || e.KeyChar == 'X'))
{
e.Handled = false;
}
//不阻止backspace
if(e.KeyChar == 8)
{
e.Handled = false;
}
}
private void txtId_TextChanged(object sender, EventArgs e)
{
pic.Visible = false;
}
}
}