当前位置: 移动技术网 > IT编程>开发语言>c# > C#结合数据库实现验证识别ID卡内容的方法

C#结合数据库实现验证识别ID卡内容的方法

2019年07月18日  | 移动技术网IT编程  | 我要评论
本文所述实例为c#结合数据库,来验证所识别的id卡内容,通过本实例代码,用户可以轻松实现对id卡会员信息的验证。该实例代码可实现读取数据库,进而逐步实现数据库连接,数据库读

本文所述实例为c#结合数据库,来验证所识别的id卡内容,通过本实例代码,用户可以轻松实现对id卡会员信息的验证。该实例代码可实现读取数据库,进而逐步实现数据库连接,数据库读取,id卡读取,id卡信息与数据库内容比对,最终返回结果并告之是否验证成功。

具体功能代码如下:

using system;
using system.collections.generic;
using system.componentmodel;
using system.data;
using system.drawing;
using system.linq;
using system.text;
using system.windows.forms;
using system.data.oledb;
using system.runtime.interopservices;
using system.diagnostics;
using system.collections;
namespace idcard
{
  public partial class form1 : form
  {
    public form1()
    {
      initializecomponent();
    }
    public delegate int hookproc(int ncode, int wparam, intptr lparam);
    static int hhook = 0;
    public const int wh_keyboard_ll = 13;
    //lowlevel键盘截获,如果是wh_keyboard=2,并不能对系统键盘截取,acrobat reader会在你截取之前获得键盘。 
    hookproc keyboardhookprocedure;
    [dllimport("kernel32")]
    public static extern int beep(int dwfreq, int dwduration);//让计算机蜂鸣
    string datapath = "";//数据库路径
    oledbconnection con;//oledbconnection对象,连接数据库
    oledbcommand cmd;//oledbcommand对象,执行sql语句
    //键盘hook结构函数 
    [structlayout(layoutkind.sequential)]
    public class keyboardhookstruct
    {
      public int vkcode;
      public int scancode;
      public int flags;
      public int time;
      public int dwextrainfo;
    }
    [dllimport("user32.dll")]
    public static extern int setwindowshookex(int idhook, hookproc lpfn, intptr hinstance, int threadid);
    [dllimport("user32.dll", charset = charset.auto, callingconvention = callingconvention.stdcall)]
    //抽掉钩子 
    public static extern bool unhookwindowshookex(int idhook);
    [dllimport("user32.dll")]
    //调用下一个钩子 
    public static extern int callnexthookex(int idhook, int ncode, int wparam, intptr lparam);
    [dllimport("kernel32.dll")]
    public static extern intptr getmodulehandle(string name);

    public string getnum(string code)
    {
      string flag = "";
      switch (code)
      {
        case "048":
          flag="0"; break;
        case "049":
          flag = "1"; break;
        case "050":
          flag = "2"; break;
        case "051":
          flag = "3"; break;
        case "052":
          flag = "4"; break;
        case "053":
          flag = "5"; break;
        case "054":
          flag = "6"; break;
        case "055":
          flag = "7"; break;
        case "056":
          flag = "8"; break;
        case "057":
          flag = "9"; break;
      }
      return flag;
    }
    public void hook_start()
    {

      // 安装键盘钩子 
      if (hhook == 0)
      {
        keyboardhookprocedure = new hookproc(keyboardhookproc);
        hhook = setwindowshookex(wh_keyboard_ll,
             keyboardhookprocedure,
            getmodulehandle(process.getcurrentprocess().mainmodule.modulename), 0);
        //如果设置钩子失败. 
        if (hhook == 0)
        {
          hook_clear(); 
        }
      }
    }

    //取消钩子事件 
    public void hook_clear()
    {
      bool retkeyboard = true;
      if (hhook != 0)
      {
        retkeyboard = unhookwindowshookex(hhook);
        hhook = 0;
      }
      //如果去掉钩子失败. 
      if (!retkeyboard) throw new exception("unhookwindowshookex failed.");
    }

    //这里可以添加自己想要的信息处理 
    string numcode="";
    public int keyboardhookproc(int ncode, int wparam, intptr lparam)
    {
      if (ncode >= 0)
      {
        if (wparam == 0x0104 || wparam == 0x0100)
        {
          keyboardhookstruct kbh = (keyboardhookstruct)marshal.ptrtostructure(lparam, typeof(keyboardhookstruct));
          int flag = kbh.vkcode;
          switch (flag)
          {
            case 96:
              numcode += "0"; break;
            case 97:
              numcode += "1"; break;
            case 98:
              numcode += "2"; break;
            case 99:
              numcode += "3"; break;
            case 100:
              numcode += "4"; break;
            case 101:
              numcode += "5"; break;
            case 102:
              numcode += "6"; break;
            case 103:
              numcode += "7"; break;
            case 104:
              numcode += "8"; break;
            case 105:
              numcode += "9"; break;
          }

          if (flag == 13)
          {
            if (numcode.length != 0)
            {
              string c = "";
              string id = "";
              for (int i = 0; i <= numcode.length - 3; i += 3)
              {
                string b = numcode.substring(i, 3);
                c += getnum(b);
              }
              id = c;
              if (id.length == 8)//如果卡号为8位
              {
                //实例化oledbconnection对象
                con = new oledbconnection("provider=microsoft.jet.oledb.4.0;data source=" + datapath);
                con.open();//打开数据库连接
                //实例化oledbcommand对象,根据id卡号检索数据表
                cmd = new oledbcommand("select * from tb_userinfo where cardid='" + id + "'", con);
                oledbdatareader sdr = cmd.executereader();//实例化oledbdatareader对象
                sdr.read();//读取记录
                txtshowcardid.text = id;//获取id卡号
                txtshowname.text = sdr["uname"].tostring();//获取员工姓名
                cbbshowsex.text = sdr["usex"].tostring();//获取员工性别
                cbbshowdep.text = sdr["udep"].tostring();//获取员工部门
                con.close();//关闭数据库连接
                beep(3000, 100);//计算机蜂鸣
              }
              numcode = "";
            }
          }

        }
      }
      return callnexthookex(hhook, ncode, wparam, lparam);
    } 



    private void form1_load(object sender, eventargs e)
    {
      cbbdep.selectedindex = 0;//设置部门下拉框的第一项被选中
      cbbsex.selectedindex = 0;//设置性别下拉框的第一项被选中
      //获取数据库路径
      datapath = application.startuppath.tostring();
      datapath = datapath.substring(0, datapath.lastindexof("\\"));
      datapath = datapath.substring(0, datapath.lastindexof("\\"));
      datapath += @"\db.mdb";
      
    }

    private void radiobutton1_checkedchanged(object sender, eventargs e)
    {
      if (radiobutton1.checked)
      {
        groupbox1.enabled = true;
        hook_clear();
      }
    }

    private void radiobutton2_checkedchanged(object sender, eventargs e)
    {
      if (radiobutton2.checked)
      {
        groupbox1.enabled = false;
        hook_start();
      }
    }

    private void button2_click(object sender, eventargs e)
    {
      txtidcard.text = "";
      txtname.text = "";
    }

    private void button1_click(object sender, eventargs e)
    {
      if (txtidcard.text == "" || txtname.text == "")//如果没有输入id卡号和员工姓名
      {
        //弹出警告信息
        if (messagebox.show("请将数据填写完整!", "警告", messageboxbuttons.ok, messageboxicon.error) == dialogresult.ok)
        {
          if (txtidcard.text == "")//如果没有输入id卡号
            txtidcard.focus();//则光标处在输入id卡号的文本框
          if (txtname.text == "")//如果没有输入员工姓名
            txtname.focus();//则光标处在输入员工姓名的文本框
          if (txtidcard.text == "" && txtname.text == "")//如果都没输入数据
            txtidcard.focus();//则光标处在输入id卡号的文本框
        }
      }
      else//如果输入了数据
      {
        if (txtidcard.text.trim().length != 8)//如果输入的id卡号不是8位
        {
          //弹出警告信息
          if (messagebox.show("id卡号必须为8位!", "警告", messageboxbuttons.ok, messageboxicon.error) == dialogresult.ok)
          {
            txtidcard.text = "";//清空输入id卡号的文本框
            txtidcard.focus();//让光标处在输入id卡号的文本框上
          }
        }
        else//如果输入的id卡号为8位
        {
          //实例化oledbconnection对象
          con=new oledbconnection("provider=microsoft.jet.oledb.4.0;data source=" + datapath);
          con.open();//打开连接
          //实例化oledbcommand对象
          cmd = new oledbcommand("select count(*) from tb_userinfo where cardid='"+txtidcard.text.trim()+"'", con);
          int flag =convert.toint32(cmd.executescalar());//判断是否已经添加过此id卡号
          if (flag > 0)//如果大于0则说明已经添加过
          {
            //弹出警告信息
            if (messagebox.show("id卡号已经添加过了!", "警告", messageboxbuttons.ok, messageboxicon.error) == dialogresult.ok)
            {
              button2_click(sender, e);//清空输入id卡号和员工姓名的文本框
            }
          }
          else//如果小于0说明没有添加过
          {
            //实例化oledbcommand对象
            cmd = new oledbcommand("insert into tb_userinfo(cardid,uname,usex,udep) values ('" + txtidcard.text.trim() + "','" + txtname.text.trim() + "','" + cbbsex.text.trim() + "','" + cbbdep.text.trim() + "')", con);
            int k = cmd.executenonquery();//执行insert语句,将输入的信息添加到数据库中
            if (k > 0)//如果大于0则操作成功
            {
              //弹出提示信息
              if (messagebox.show("添加成功!", "提示", messageboxbuttons.ok, messageboxicon.information) == dialogresult.ok)
              {
                button2_click(sender, e);//清空输入id卡号和员工姓名的文本框
              }
            }
          }
          con.close();//关闭数据库连接
        }
      }
    }

    private void txtidcard_keypress(object sender, keypresseventargs e)
    {
      if (!(e.keychar <= '9' && e.keychar >= '0') && e.keychar != '\r' && e.keychar != '\b')
      {
        e.handled = true;
      }
    }
  }
}

该实例注释完善,便于阅读,读者还可以根据自身需求改善代码,或者添加新的功能以满足自身应用的个性化需求。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网