private string _sComPortNumber; private bool _bFoundPortNumber; private System.Windows.Forms.Control _oStaticShow; private System.IO.Ports.SerialPort _oCIMControler; ////// COM口名 /// public string ComPortName { get { return _sComPortNumber; } } ////// 编码 /// public Encoding StringEncoding { get; set; } ////// 比特率 /// public int BaudRate { get; set; } ////// 数据位 /// public int DataBits { get; set; } ////// 奇偶检验 /// public System.IO.Ports.Parity Parity { get; set; } ////// 停止位 /// public System.IO.Ports.StopBits StopBits { get; set; } private bool OpenPortAndSendMsg() { foreach (string tmpName in System.IO.Ports.SerialPort.GetPortNames()) { foreach (string sCurrentMachinePortNumber in System.IO.Ports.SerialPort.GetPortNames()) { try { if (_bFoundPortNumber == false) { System.IO.Ports.SerialPort otmpsp = new System.IO.Ports.SerialPort(); otmpsp.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(otmpsp_DataReceived); otmpsp.PortName = sCurrentMachinePortNumber; otmpsp.BaudRate = this.BaudRate; otmpsp.DataBits = this.DataBits; otmpsp.Parity = this.Parity; otmpsp.StopBits = this.StopBits; otmpsp.Open(); //写数据************************ otmpsp.Write(new byte[] { 2 }, 0, 1); string Command = "ST"; otmpsp.Write(Command); otmpsp.Write(new byte[] { 3 }, 0, 1); otmpsp.Write(new byte[] { 6 }, 0, 1); otmpsp.Write(new byte[] { 5 }, 0, 1); //**************************** System.Threading.Thread.Sleep(500); otmpsp.Close(); } else { return true; } } catch (Exception ex) { } } } return false; } void otmpsp_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { System.IO.Ports.SerialPort oSenderObject = sender as System.IO.Ports.SerialPort; if (oSenderObject.BytesToWrite > 0) { oSenderObject.BaseStream.Flush(); } int iReadFlag = oSenderObject.BytesToRead; while (iReadFlag > 0) { string sReturn = oSenderObject.ReadExisting(); if (sReturn.Contains("")) { _bFoundPortNumber = true; _sComPortNumber = oSenderObject.PortName; } iReadFlag = oSenderObject.BytesToRead; } }