日期:2014-05-17 浏览次数:21392 次
private SerialPort _ComPort = new SerialPort(); private void InitializeObject() { InitPortsToList(); //初始化SerialPort对象 this._ComPort.NewLine = "\r\n"; this._ComPort.RtsEnable = true; this._ComPort.DataReceived += new SerialDataReceivedEventHandler(ComPort_DataReceived); }
private void btnConnect_Click(object sender, EventArgs e) { //根据当前串口对象,来判断操作 if (this._ComPort.IsOpen) { //打开时点击,则关闭串口 this._ComPort.Close(); } else { //关闭时点击,则设置好端口,波特率后打开 this._ComPort.PortName = this.cmbPort.Text; this._ComPort.BaudRate = int.Parse(this.cmbBaudrate.Text); try { this._ComPort.Open(); } catch (Exception ex) { //捕获到异常信息,创建一个新的comm对象,之前的不能用了。 this._ComPort = new SerialPort(); this._ComPort.PortName = this.cmbPort.Text; //COM1 this._ComPort.BaudRate = int.Parse(this.cmbBaudrate.Text); //9600 this._ComPort.Open(); //现实异常信息给客户。 MessageBox.Show(ex.Message); } } }
List<byte> buffer = new List<byte>(); byte[] tmp = { 10 }; //这里的10是厂家说明书里的命令 16进制是0x0A,10进制是10,表示打印并换行 string content = this.txtContent.Text.Trim(); //这里是打印的内容 byte[] dataContent = Encoding.Default.GetBytes(content); buffer.AddRange(dataContent); buffer.AddRange(tmp); byte[] data = buffer.ToArray(); this._ComPort.Write(data, 0, data.Length); this._ComPort.Close();