日期:2014-05-18 浏览次数:21168 次
//你的有个serialPort控件. /// <summary> /// serialPort的DataReceived事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { try { byte[] buffer = new byte[serialPort1.BytesToRead]; serialPort1.Read(buffer, 0, buffer.Length); string strID = ""; for (int i = 0; i < buffer.Length; i++) { strID = strID + String.Format("{0:X2}", buffer[i]); } this.Invoke(interfaceUpdateHandle, strID); } catch (Exception ex) { MessageBox.Show(ex.Message, "读卡错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } } //弄个委托 delegate void HandleInterfaceUpdateDelegate(String text); HandleInterfaceUpdateDelegate interfaceUpdateHandle; public CPLoginForm() { InitializeComponent(); interfaceUpdateHandle = new HandleInterfaceUpdateDelegate(QueryIDCard);//读卡 CloseSerialPort();//关闭serialPort OpenSerialPort();//开启serialPort } /// <summary> /// 检索Id卡 /// </summary> /// <param name="strPass"></param> private void QueryIDCard(string strPass) { DataTable dt_id = GetID(strPass);//用读卡器传来的数据验证,这句话是连数据库的,你不用在意. if (dt_id.Rows.Count <= 0) MessageBox.Show("无效的ID卡!", "注意", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); else { //验证通过,你可以做你喜欢的~ } } //关闭SerialPort private void CloseSerialPort() { if (this.serialPort1.IsOpen) { Application.DoEvents(); serialPort1.Close(); } } //打开串口 private void OpenSerialPort() { try { if (serialPort1.IsOpen) { CloseSerialPort(); } else { serialPort1.Open(); } } catch (Exception ex) { if (idts) { MessageBox.Show("请更改配置文件中的串口设置,错误信息如下:\r\n" + ex.Message, "无法打开串口设备", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } //以上为自己写的代码,功能倒是实现了,但是有点丑,请各位多指正.