欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

基于C#實現(xiàn)員工IC卡的讀寫功能

 更新時間:2023年01月03日 09:37:40   作者:芝麻粒兒  
這篇文章主要為大家詳細介紹了C#如何實現(xiàn)讀寫員工IC卡的功能,文中的示例代碼講解詳細,對我們學習C#有一定的幫助,感興趣的小伙伴可以跟隨小編一起了解一下

實踐過程

效果

代碼

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 系統(tǒng)信息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卡只讀取一次以及向數(shù)據(jù)庫中只添加一次內(nèi)容
    int flag2 = -1;//設置的一個變量,用于控制當某個IC卡已經(jīng)參加考勤后,彈出一次錯誤提示
    private void timer1_Tick(object sender, EventArgs e)
    {
        int i = baseClass.ReadIC(txtICCard);//調(diào)用公共類中的ReadIC方法開始循環(huán)讀取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的時候執(zhí)行
            {
                string icID = txtICCard.Text.Trim();//獲取讀取的IC卡編號
                if (baseClass.isCheck(icID))//isCheck方法判斷是否參加過考勤
                {
                    if (flag2 == -1)//只有當flag2為-1的時候執(zhí)行
                    {
                        flag2 = 0;//改變標記的值從而實現(xiàn)只彈出一次警告對話框
                        MessageBox.Show("已經(jīng)參加過考勤!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        //清空文本框
                        txtDept.Text = "";
                        txtFolk.Text = "";
                        txtICCard.Text = "";
                        txtJob.Text = "";
                        txtName.Text = "";
                        txtSex.Text = "";
                        txtICCard.Text = "";
                        groupBox1.Text = "考勤進行中";
                    }
                }
                else//如果沒有參加過考勤
                {
                    //調(diào)用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();//員工部門
                    //聲明一個字符串,用于存儲一條插入語句,實現(xiàn)將考勤信息插入到數(shù)據(jù)表中
                    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方法執(zhí)行SQL語句
                    tsslEinfo.Text = "已經(jīng)有"+baseClass.GetNum(DateTime.Now.ToShortDateString())+"人參加考勤";
                }
            }
            flag = 0;//改變flag的值實現(xiàn)一張IC卡只存儲一次信息

        }
    }

    private void 退出系統(tǒng)ToolStripMenuItem_Click(object sender, EventArgs e)
    {
        Application.Exit();
    }

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

    private void 考勤結(jié)束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卡的數(shù)據(jù)
                string name = txtName.Text.Trim();//員工姓名
                string sex = 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卡編號已經(jīng)存在!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    if (baseClass.WriteIC(icID) == 0)//WriteIC方法將編號寫入IC卡,如果成功則返回0
                    {
                        //聲明一條語句,用于將員工其他信息插入到數(shù)據(jù)表中
                        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方法執(zhí)行這條語句
                        {
                            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 使用動態(tài)鏈接庫,聲明方法
[StructLayout(LayoutKind.Sequential)]
public unsafe class IC
{
    //對設備進行初始化
    [DllImport("Mwic_32.dll", EntryPoint = "auto_init", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, 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);
    //獲取設備當前狀態(tài)
    [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);
    //使設備發(fā)出蜂鳴聲
    [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卡中寫數(shù)據(jù)
    [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卡中數(shù)據(jù)
    [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("設備當前狀態(tài)錯誤!");
                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);  //發(fā)出蜂鳴聲
            }
            else
                MessageBox.Show("數(shù)據(jù)寫入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("設備當前狀態(tài)錯誤!");
                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);  //發(fā)出蜂鳴聲
            }
            if (read == 0)
            {
                ff = 0;
                flag = read;
            }
        }
        int d = IC.ic_exit(icdev);  //關閉設備
        return flag;
    }

    public static bool ExecuteSQL(string sql)//執(zhí)行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卡號是否已經(jīng)存在
    {
        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)//根據(jù)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)//導出數(shù)據(jù),傳入一個datagridview和一個文件路徑
    {

        string type = fileName.Substring(fileName.IndexOf(".") + 1);//獲得數(shù)據(jù)類型
        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++)//填充數(shù)據(jù)
                {
                    for (int j = 0; j < srcDgv.Columns.Count; j++)
                    {
                        if (srcDgv[j, i].ValueType.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.Table 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++)//填充數(shù)據(jù)
                {
                    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); //將數(shù)據(jù)庫中的圖片轉(zhuǎn)換成二進制流
                            MemoryStream ms = new MemoryStream(pic);	//將字節(jié)數(shù)組存入到二進制流中
                            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)//檢查是否已經(jīng)參加過考勤
    {
        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 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)//獲取所有參加考勤的人數(shù)
    {
        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#實現(xiàn)員工IC卡的讀寫功能的文章就介紹到這了,更多相關C#讀寫員工IC卡內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論