开发者

基于C#实现员工IC卡的读写功能

开发者 https://www.devze.com 2023-01-03 10:30 出处:网络 作者: 芝麻粒儿
目录实践过程效果代码实践过程 效果 代码 public partial class Form1 : Form { public Form1()
目录
  • 实践过程
    • 效果
    • 代码

实践过程

效果

基于C#实现员工IC卡的读写功能

基于C#实现员工IC卡的读写功能

基于C#实现员工IC卡的读写功能

代码

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        lblTime.Text = DateTime.Now.ToString();//当进行考勤的时候在窗体中显示当前时间
        tsslTime.Text = DateTime.Now.ToString();//在任务栏中显示当前时间
    }

    private void 添加员工ToolStripMenuItem_Click(object sender, EventArgs e)
    {
        Form2 frm2 = new Form2();
        frm2.ShowDialog();
    }

    private void 系统信息ToolStripMenuItem_Click(object sender, EventArgs e)
    {
        System.Diagnostics.Process.Start("MSINFO32.EXE");
    }

    private void 开始考勤ToolStripMenuItem_Click(object sender, EventArgs e)
    {
        timer1.Start();//开始考勤
        panel1.Visible = true;//显示考勤界面
        timer2.Start();//开始显示当前时间
        开始考勤ToolStripMenuItem.Enabled = false;//禁用开始考勤菜单
    }

    int flag = -1;//设置的一个变量,用于控制一张IC卡只读取一次以及向数据库中只添加一次内容
    int flag2 = -1;//设置的一个变量,用于控制当某个IC卡已经参加考勤后,弹出一次错误提示
    private void timer1_Tick(object sender, EventArgs e)
    {
        int i = baseClass.ReadIC(txtICCard);//调用公共类中的ReadIC方法开始循环读取IC卡
        if (i == -1)//如果返回值是-1说明没有IC卡
        {
            //清空显示员工信息的文本框
            txtDept.Text = "";
            txtFolk.Text = "";
            txtICCard.Text = "";
            txtJob.Text = "";
            txtName.Text = "";
            txtSex.Text = "";
            groupBox1.Text = "考勤进行中";
            flag = -1;//初始化标记
            flag2 = -1;//初始化标记
        }
        else//如果有IC卡进行考勤
        {
            if (flag ==-1)//只有当flag为-1的时候执行
            {
                string icID = txtICCard.Text.Trim();//获取读取的IC卡编号
                if (baseClass.isCheck(icID))//isCheck方法判断是否参加过考勤
                {
                    if (flag2 == -1)//只有当flag2为-1的时候执行
                    {
                        flag2 = 0;//改变标记的值从而实现只弹出一次警告对话框
                        MessageBox.Show("已经参加过考勤!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        //清空文本框
                        txtDept.Text = "";
                        txtFolk.Text = "";
                        txtICCard.Text = "";
                        txtJob.Text = "";
                        txtName.Text = "";
                        txtSex.Text = "";
                        txtICCard.Text = "";
                        groupBox1.Text = "考勤进行中";
                    }
                }
       js         else//如果没有参加过考勤
                {
                    //调用GetInfo方法获取IC卡对应的员工信息
                    baseClass.GetInfo(txtICCard.Text.Trim(), txtName, txtSex, txtJob, txtFolk, txtDept, groupBox1);
                    string name = txtName.Text.Trim();//员工姓名
                    string sex = txtSex.Text.Trim();//员工性别
                    string job = txtJob.Text.Trim();//员工职位
                    string folk = this.txtFolk.Text.Trim();//员工民族
                    string dept = txtDept.Text.Trim();//员工部门
                    //声明一个字符串,用于存储一条插入语句,实现将考勤信息插入到数据表中
                    string str = "insert into CheckNote(C_CardID,C_Name,C_Sex,C_Job,C_Folk,C_Dept,C_Time) values('" + icID + "','" + name + "','" + sex + "','" + job + "','" + folk + "','" + dept + "','" + DateTime.Now.ToShortDateString() + "')";
                    baseClass.ExecuteSQL(str);//ExecuteSQL方法执行SQL语句
                    tsslEinfo.Text = "已经有"+baseClass.GetNum(DateTime.Now.ToShortDateString())+"人参加考勤";
                }
            }
            flag = 0;//改变flag的值实现一张IC卡只存储一次信息

        }
    }

    private void 退出系统ToolStripMenuItem_Click(object sender, EventArgs e)
    {
        Application.Exit();
    }

    private void timer2_Tick(object sender, EventArgs e)
    {
        lblTime.Text = DateTime.Now.ToString();
    }

    private void 考勤结束ToolStripMenuItem_Click(object sender, EventArgs e)
    {
        开始考勤ToolStripMenuItem.Enabled = true;
        panel1.Visible = false;
        timer1.Stop();
        timer2.Stop();
        tsslEinfo.Text = "";
    }

    private void 考勤记录ToolStripMenuItem_Click(object sender, EventArgs e)
    {
        Form3 frm3 = new Form3();
        frm3.ShowDialog();
    }

    private void timer3_Tick(object sender, EventArgs e)
    {
        tsslTime.Text = DateTime.Now.ToString();
    }

    private void 关于ToolStripMenuItem_Click(object sender, EventArgs e)
    {
        AboutBox1 ab = new AboutBox1();
        ab.ShowDialog();
    }
}
 public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void Form2_Load(object sender, EventArgs e)
        {
            cbFolk.SelectedIndex = 0;//民族选项默认第一项被选中
            cbSex.SelectedIndex = 0;//性别选项默认第一项被选中
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (txtDept.Text == "" || txtICCard.Text == "" || txtJob.Text == "" || txtName.Text == "")
            {
                MessageBox.Show("请将信息输入完整!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                string icID = txtICCard.Text.Trim();//要写入IC卡的数据
                string name = txtName.Text.Trim();//员工姓名
                string sehttp://www.devze.comx = cbSex.Text.Trim();//员工性别
                string job = txtJob.Text.Trim();//员工职位
                string folk= cbFolk.Text.Trim();//员工民族
                string dept = txtDept.Text.Trim();//员工部门
                if (baseClass.CheckID(icID))//CheckID方法检查编号是否存在
                {
                    MessageBox.Show("IC卡编号已经存在!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    if (baseClass.WriteIC(icID) == 0)//WriteIC方法将编号写入IC卡,如果成功则返回0
                    {
                        //声明一条语句,用于将员工其他信息插入到数据表中
                        string strSQL = "insert into Employee(CardID,E_Name,E_Sex,E_Job,E_Folk,E_Dept,E_Time) values('" + icID + "','" + name + "','" + sex + "','" + job + "','" + folk + "','" + dept + "','"+DateTime.Now.ToShortDateString()+"')";
                        if (baseClass.ExecuteSQL(strSQL))//ExecuteSQL方法执行这条语句
                        {
                            MessageBox.Show("IC卡注册完毕!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                }
            }
        }

        private void txtICCard_TextChanged(object sender, EventArgs e)
        {
            if (Regex.IsMatch(txtICCard.Text.Trim(), "[\u4e00-\u9fa5]"))
            {
                MessageBox.Show("禁止输入汉字!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
    }
#region 使用动态链接库,声明方法
[StructLayout(LayoutKind.Sequential)]
public unsafe class IC
{
    //对设备进行初始化
    [DllImport("Mwic_32.dll", EntryPoint = "auto_init", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true开发者_Python开发, CallingConvention = CallingConvention.StdCall)]
    public static extern int auto_init(int port, int baud);
    //设备密码格式
    [DllImport("Mwic_32.dll", EntryPoint = "setsc_md", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern int setsc_md(int icdev, int mode);
    //获取设备当前状态
    [DllImport("Mwic_32.dll", EntryPoint = "get_status", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern Int16 get_status(int icdev, Int16* state);
    //关闭设备通讯接口
    [DllImport("Mwic_32.dll", EntryPoint = "ic_exit", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern int ic_exit(int icdev);
    //使设备发出蜂鸣声
    [DllImport("Mwic_32.dll", EntryPoint = "dv_beep", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern int dv_beep(int icdev, int time);
    //向IC卡中写数据
    [DllImport("Mwic_32.dll", EntryPoint = "swr_4442", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern int swr_4442(int icdev, int offset, int len, char* w_string);
    //读取IC卡中数据
    [DllImport("Mwic_32.dll", EntryPoint = "srd_4442", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern int srd_4442(int icdev, int offset, int len, char* r_string);
    //核对卡密码  
    [DllImport("Mwic_32.dll", EntryPoint = "csc_4442", SetLastError = true, CharSet = CharSet.Auto, ExactSpelling = true, CallingConvention = CallingConvention.Winapi)]
    public static extern Int16 Csc_4442(int icdev, int len, [MarshalAs(UnmanagedType.LPArray)] byte[] p_string);
}
#endregion

class baseClass
{
    public static int WriteIC(string id)//写入IC卡的方法
    {
        int flag = -1;
        //初始化
        int icdev = IC.auto_init(0, 9600);
        if (icdev < 0)
            MessageBox.Show("端口初始化失败,请检查接口线是否连接正确。", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        int md = IC.setsc_md(icdev, 1); //设备密码格式
        unsafe
        {
            Int16 status = 0;
            Int16 result = 0;
            result = IC.get_status(icdev, &status);
            if (result != 0)
            {
                MessageBox.Show("设备当前状态错误!");
                int d1 = IC.ic_exit(icdev);   //关闭设备
            }
            if (status != 1)
            {
                MessageBox.Show("请插入IC卡");
                int d2 = IC.ic_exit(icdev);   //关闭设备
            }
        }
        unsafe
        {
            //卡的密码默认为6个F(密码为:ffffff),1个F的16进制是15,2个F的16进制是255。
            byte[] pwd = new byte[3] { 0xff, 0xff, 0xff };
            Int16 checkIC_pwd = IC.Csc_4442(icdev, 3, pwd);
            if (checkIC_pwd < 0)
            {
                MessageBox.Show("IC卡密码错误!");
            }
            char str = 'a';
            int write = -1;
            for (int j = 0; j < id.Length; j++)
            {
                str = Convert.ToChar(id.Substring(j, 1));
                write = IC.swr_4442(icdev, 33 + j, id.Length, &str);
            }
            if (write == 0)
            {
                flag = write;
                int beep = IC.dv_beep(icdev, 20);  //发出蜂鸣声
            }
            else
                MessageBox.Show("数据写入IC卡失败!");
        }
        int d = IC.ic_exit(icdev);  //关闭设备
        return flag;
    }

    public static int ff = -1;
    public static int ReadIC(TextBox tb)//读取IC卡
    {
        int flag = -1;
        //初始化
        int icdev = IC.auto_init(0, 9600);
        if (icdev < 0)
            MessageBox.Show("端口初始化失败,请检查接口线是否连接正确。", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        int md = IC.setsc_md(icdev, 1); //设备密码格式
        unsafe
        {
            Int16 status = 0;
            Int16 result = 0;
            result = IC.get_status(icdev, &status);
            if (result != 0)
            {
                MessageBox.Show("设备当前状态错误!");
                int d1 = IC.ic_exit(icdev);   //关闭设备
            }

            if (status != 1)
            {
                ff = -1;
                int d2 = IC.ic_exit(icdev);   //关闭设备
            }
        }
        unsafe
        {
            char str;
            int read = -1;
            string ic = "";
            for (int j = 0; j < 6; j++)
            {
                read = IC.srd_4442(icdev, 33 + j, 1, &str);
                ic = ic + Convert.ToString(str);
            }
            tb.Text = ic;
            if (ff == -1)
            {
                int i = IC.dv_beep(icdev, 10);  //发出蜂鸣声
            }
            if (read == 0)
            {
                ff = 0;
                flag = read;
            }
        }
        int d = IC.ic_exit(icdev);  //关闭设备
        return flag;
    }

    public static bool ExecuteSQL(string sql)//执行SQL语句
    {
        bool flag = false;
        string strg = Application.StartupPath.ToString();
        strg = strg.Substring(0, strg.LastIndexOf("\\"));
        strg = strg.Substring(0, strg.LastIndexOf("\\"));
        strg += @"\db1.mdb";
        OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data source=" + strg);
        conn.Open();
        OleDbCommand cmd = new OleDbCommand(sql, conn);
        int i = cmd.ExecuteNonQuery();
        if (i > 0)
        {
            flag = true;
            conn.Close();
        }
        return flag;
    }

    public static bool CheckID(string id)//判断输入的IC卡号是否已经存在
    {
        bool flag = false;
        string strg = Application.StartupPath.ToString();
        strg = strg.Substring(0, strg.LastIndexOf("\\"));
        strg = strg.Substring(0, strg.LastIndexOf("\\"));
        strg += @"\db1.mdb";
        OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data source=" + strg);
        conn.Open();
        OleDbCommand cmd = new OleDbCommand("select Count(*) from Employee where CardID='"+id+"'", conn);
        int i = Convert.ToInt32(cmd.ExecuteScalar());
        conn.Close();
        if (i > 0)
        {
            flag = true;
        }
        return flag;
    }

    public static void GetInfo(string id,TextBox name,TextBox sex,TextBox job,TextBox folk,TextBox dept,GroupBox gb)//根据IC卡号获取相应的信息
    {
        if (CheckID(id))
        {
            string strg = Application.StartupPath.ToString();
            strg = strg.Substring(0, strg.LastIndexOf("\\"));
            strg = strg.Substring(0, strg.LastIndexOf("\\"));
            strg += @"\db1.mdb";
            OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data source=" + strg);
            conn.Open();
            OleDbCommand cmd = new OleDbCommand("select * from Employee where CardID='" + id + "'", conn);
            OleDbDataReader sdr = cmd.ExecuteReader();
            sdr.Read();
            name.Text = sdr["E_Name"].ToString();
            sex.Text = sdr["E_Sex"].ToString();
            job.Text = sdr["E_Job"].ToString();
            folk.Text = sdr["E_Folk"].ToString();
            dept.Text = sdr["E_Dept"].ToString();
            gb.Text = "考勤进行中(考勤成功)";
            sdr.Close();
            conn.Close();
        }
        else
        {
            gb.Text = "考勤进行中(此IC卡未被注册!)";
        }
    }

    public static void ExportData(DataGridView srcDgv, string fileName)//导出数据,传入一个datagridview和一个文件路径
    {

        string type = fileName.Substring(fileName.IndexOf(".") + 1);//获得数据类型
        if (type.Equals("xls", StringComparison.CurrentCultureIgnoreCase))//Excel文档
        {
            Excel.Application excel = new Excel.Application();
            try
            {
                excel.DisplayAlerts = false;
                excel.Workbooks.Add(true);
                excel.Visible = false;

                for (int i = 0; i < srcDgv.Columns.Count; i++)//设置标题
                {
                    excel.Cells[2, i + 1] = srcDgv.Columns[i].HeaderText;
                }

                for (int i = 0; i < srcDgv.Rows.Count; i++)//填充数据
                {
                    for (int j = 0; j < srcDgv.Columns.Count; j++)
                    {
                        if (srcDgv[j, i].Val编程客栈ueType.ToString() == "System.Byte[]")
                        {
                            excel.Cells[i + 3, j + 1] = "System.Byte[]";
                        }
                        else
                        {
                            excel.Cells[i + 3, j + 1] = srcDgv[j, i].Value;
                        }
                    }
                }

                excel.Workbooks[1].SaveCopyAs(fileName);//保存
            }
            finally
            {
                excel.Quit();
            }
            return;
        }
        //保存Word文件
        if (type.Equals("doc", StringComparison.CurrentCultureIgnoreCase))
        {

            object path = fileName;
            Object none = System.Reflection.Missing.Value;
            Word.Application wordApp = new Word.Application();
            Word.Document document = wordApp.Documents.Add(ref none, ref none, ref none, ref none);
            //建立表格
            Word.T编程客栈able table = document.Tables.Add(document.Paragraphs.Last.Range, srcDgv.Rows.Count + 1, srcDgv.Columns.Count, ref none, ref none);
            try
            {

                for (int i = 0; i < srcDgv.Columns.Count; i++)//设置标题
                {
                    table.Cell(1, i + 1).Range.Text = srcDgv.Columns[i].HeaderText;
                }

                for (int i = 0; i < srcDgv.Rows.Count; i++)//填充数据
                {
                    for (int j = 0; j < srcDgv.Columns.Count; j++)
                    {
                        string a = srcDgv[j, i].ValueType.ToString();
                        if (a == "System.Byte[]")
                        {
                            PictureBox pp = new PictureBox();
                            byte[] pic = (byte[])(srcDgv[j, i].Value); //将数据库中的图片转换成二进制流
                            MemoryStream ms = new MemoryStream(pic);	//将字节数组存入到二进制流中
                            pp.Image = Image.FromStream(ms);           //二进制流Image控件中显示
                            pp.Image.Save(@"C:\22.bmp");               //将图片存入到指定的路径
                            object aaa = table.Cell(i + 2, j + 1).Range;
                            wordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                            wordApp.Selection.InlineShapes.AddPicture(@"C:\22.bmp", ref none, ref none, ref aaa);
                            pp.Dispose();
                        }
                        else
                        {
                            table.Cell(i + 2, j + 1).Range.Text = srcDgv[j, i].Value.ToString();
                        }
                    }
                }
                document.SaveAs(ref path, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none);
                document.Close(ref none, ref none, ref none);
                if (File.Exists(@"C:\22.bmp"))
                {
                    File.Delete(@"C:\22.bmp");
                }
            }
            finally
            {
                wordApp.Quit(ref none, ref none, ref none);
            }
        }
    }

    public static void BinddataGridView(DataGridView dg, string datetime)
    {
        string strg = Application.StartupPath.ToString();
        strg = strg.Substring(0, strg.LastIndexOf("\\"));
        strg = strg.Substring(0, strg.LastIndexOf("\\"));
        strg += @"\db1.mdb";
        OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data source=" + strg);
        conn.Open();
        string str = "select C_CardID as IC卡编号,C_Name as 员工姓名,C_Sex as 性别,C_Job as 职位,C_Folk as 民族,C_Dept as 员工部门,C_Time as 考勤日期 from CheckNote where C_Time='" + datetime + "'";
        OleDbDataAdapter da = new OleDbDataAdapter(str, conn);
        System.Data.DataTable dt = new System.Data.DataTable();
        da.Fill(dt);
        dg.DataSource = dt;
        dg.Columns[0].Width = 80;
        dg.Columns[1].Width = 80;
        dg.Columns[2].Width = 60;
        dg.Columns[3].Width = 60;
        dg.Columns[4].Width = 60;
        dg.Columns[5].Width = 80;
        dg.Columns[6].Width = 80;
        conn.Close();
    }

    public static bool isCheck(string id)//检查是否已经参加过考勤
    {
        bool flag = false;
        string strg = Application.StartupPath.ToString();
        strg = strg.Substring(0, strg.LastIndexOf("\\"));
        strg = strhttp://www.devze.comg.Substring(0, strg.LastIndexOf("\\"));
        strg += @"\db1.mdb";
        OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data source=" + strg);
        conn.Open();
        OleDbCommand cmd = new OleDbCommand("select Count(*) from CheckNote where C_CardID='" + id + "'", conn);
        int i = Convert.ToInt32(cmd.ExecuteScalar());
        conn.Close();
        if (i > 0)
        {
            flag = true;
        }
        return flag;
    }

    public static int GetNum(string datetime)//获取所有参加考勤的人数
    {
        string strg = Application.StartupPath.ToString();
        strg = strg.Substring(0, strg.LastIndexOf("\\"));
        strg = strg.Substring(0, strg.LastIndexOf("\\"));
        strg += @"\db1.mdb";
        OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data source=" + strg);
        conn.Open();
        OleDbCommand cmd = new OleDbCommand("select Count(*) from CheckNote where C_Time='" + datetime + "'", conn);
        int i = Convert.ToInt32(cmd.ExecuteScalar());
        conn.Close();
        return i;
    }
}

到此这篇关于基于C#实现员工IC卡的读写功能的文章就介绍到这了,更多相关C#读写员工IC卡内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号