C combines with database to realize the method of authentication and identification of ID card content

  • 2020-06-23 01:48:55
  • OfStack

The example described in this paper is C# combined with the database to verify the recognized ID card content. Through this example code, users can easily realize the authentication of ID card membership information. The example code can read the database, and then gradually realize the database connection, database read, ID card read, ID card information and database content comparison, and finally return the result and tell whether the verification is successful.

The specific function code is as follows:


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 Keyboard interception, if yes WH_KEYBOARD = 2 , cannot intercept the system keyboard, Acrobat Reader It will get the keyboard before you intercept it.  
    HookProc KeyBoardHookProcedure;
    [DllImport("kernel32")]
    public static extern int Beep(int dwFreq, int dwDuration);// Let the computer buzz 
    string DataPath = "";// Database path 
    OleDbConnection con;//OleDbConnection Object to connect to the database 
    OleDbCommand cmd;//OleDbCommand Object, execute SQL statements 
    // The keyboard Hook Structure function  
    [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)]
    // Take off the hook  
    public static extern bool UnhookWindowsHookEx(int idHook);
    [DllImport("user32.dll")]
    // Under the call 1 A hook  
    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()
    {

      //  Install keyboard hooks  
      if (hHook == 0)
      {
        KeyBoardHookProcedure = new HookProc(KeyBoardHookProc);
        hHook = SetWindowsHookEx(WH_KEYBOARD_LL,
             KeyBoardHookProcedure,
            GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName), 0);
        // If setting the hook fails . 
        if (hHook == 0)
        {
          Hook_Clear(); 
        }
      }
    }

    // Unhook event  
    public void Hook_Clear()
    {
      bool retKeyboard = true;
      if (hHook != 0)
      {
        retKeyboard = UnhookWindowsHookEx(hHook);
        hHook = 0;
      }
      // If removing the hook fails . 
      if (!retKeyboard) throw new Exception("UnhookWindowsHookEx failed.");
    }

    // Here you can add the information processing you want  
    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)// If the card number is 8 position 
              {
                // instantiation OleDbConnection object 
                con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data source=" + DataPath);
                con.Open();// Open database connection 
                // instantiation OleDbCommand Object, according to ID The card number retrieves the data table 
                cmd = new OleDbCommand("select * from tb_UserInfo where CardID='" + id + "'", con);
                OleDbDataReader sdr = cmd.ExecuteReader();// instantiation OleDbDataReader object 
                sdr.Read();// Read the record 
                txtShowCardID.Text = id;// To obtain ID The card number 
                txtShowName.Text = sdr["UName"].ToString();// Get employee names 
                cbbShowSex.Text = sdr["USex"].ToString();// Obtain employee gender 
                cbbShowDep.Text = sdr["UDep"].ToString();// Acquisition staff department 
                con.Close();// Close the database connection 
                Beep(3000, 100);// Computer buzz 
              }
              NumCode = "";
            }
          }

        }
      }
      return CallNextHookEx(hHook, nCode, wParam, lParam);
    } 



    private void Form1_Load(object sender, EventArgs e)
    {
      cbbdep.SelectedIndex = 0;// Set the control of the department drop-down box 1 Item is selected 
      cbbsex.SelectedIndex = 0;// Sets the control of the gender drop-down box 1 Item is selected 
      // Get the database path 
      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 == "")// If there is no input ID Card number and employee name 
      {
        // Pop-up warning message 
        if (MessageBox.Show(" Please fill in the data completely! ", " warning ", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
        {
          if (txtIdcard.Text == "")// If there is no input ID The card number 
            txtIdcard.Focus();// The cursor is at the input ID The text box for the card number 
          if (txtName.Text == "")// If the employee name is not entered 
            txtName.Focus();// The cursor is in the text box where the employee's name is entered 
          if (txtIdcard.Text == "" && txtName.Text == "")// If no data is entered 
            txtIdcard.Focus();// The cursor is at the input ID The text box for the card number 
        }
      }
      else// If you enter data 
      {
        if (txtIdcard.Text.Trim().Length != 8)// If the input ID Card number is not 8 position 
        {
          // Pop-up warning message 
          if (MessageBox.Show("ID The card number must be 8 A!!!! ", " warning ", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
          {
            txtIdcard.Text = "";// Empty the input ID The text box for the card number 
            txtIdcard.Focus();// Put the cursor on the input ID On the text box of the card number 
          }
        }
        else// If the input ID Card number is 8 position 
        {
          // instantiation OleDbConnection object 
          con=new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data source=" + DataPath);
          con.Open();// Open the connection 
          // instantiation OleDbCommand object 
          cmd = new OleDbCommand("select count(*) from tb_UserInfo where CardID='"+txtIdcard.Text.Trim()+"'", con);
          int flag =Convert.ToInt32(cmd.ExecuteScalar());// Determine if this has been added ID The card number 
          if (flag > 0)// If more than 0 Indicates that it has been added 
          {
            // Pop-up warning message 
            if (MessageBox.Show("ID The card number has been added! ", " warning ", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
            {
              button2_Click(sender, e);// Empty the input ID Text box for card number and employee name 
            }
          }
          else// If less than 0 Note that it has not been added 
          {
            // instantiation OleDbCommand object 
            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();// perform insert Statement to add the input information to the database 
            if (k > 0)// If more than 0 Then the operation is successful 
            {
              // Pop-up prompt message 
              if (MessageBox.Show(" Added successfully! ", " prompt ", MessageBoxButtons.OK, MessageBoxIcon.Information) == DialogResult.OK)
              {
                button2_Click(sender, e);// Empty the input ID Text box for card number and employee name 
              }
            }
          }
          con.Close();// Close the database connection 
        }
      }
    }

    private void txtIdcard_KeyPress(object sender, KeyPressEventArgs e)
    {
      if (!(e.KeyChar <= '9' && e.KeyChar >= '0') && e.KeyChar != '\r' && e.KeyChar != '\b')
      {
        e.Handled = true;
      }
    }
  }
}

This example is well commented and easy to read, and readers can also improve the code according to their own needs, or add new functions to meet their own application personalized needs.


Related articles: