using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO.Ports; using System.Threading; using System.Windows.Forms; namespace DisassemblyTable { public class SerialHelper { public delegate void EventHandle(byte[] readBuffer); public event EventHandle DataReceived; public System.IO.Ports.SerialPort serialPort; Thread thread; volatile bool _keepReading; public SerialHelper() { serialPort = new System.IO.Ports.SerialPort(); thread = null; _keepReading = false; } public bool IsOpen { get { return serialPort.IsOpen; } } private void StartReading() { if (!_keepReading) { _keepReading = true; thread = new Thread(new ThreadStart(ReadPort)); thread.Start(); } } private void StopReading() { if (_keepReading) { _keepReading = false; thread.Join(); thread = null; } } private void ReadPort() { while (_keepReading) { if (serialPort.IsOpen) { //接受数据的字节数 if (serialPort.BytesToRead > 0) { Thread.Sleep(100); int count = serialPort.BytesToRead; byte[] readBuffer = new byte[count]; try { Application.DoEvents(); serialPort.Read(readBuffer, 0, count); if(DataReceived != null) DataReceived(readBuffer); } catch (TimeoutException) { } } } } } public void Open() { if (serialPort.IsOpen) { Close(); } try { serialPort.Open(); if (serialPort.IsOpen) { StartReading(); } else { //ICSharpCode.Core.LoggingService.Debug("端口打开失败"); } } catch { MessageBox.Show(serialPort.PortName+":无此端口或已被占用"); //ICSharpCode.Core.LoggingService.Debug("无此端口或已被占用:"); } } public bool Writetxt(string txt) { try { if (!IsOpen) { Open(); } serialPort.Write(txt); return true; } catch { return false; } } public void Close() { StopReading(); serialPort.Close(); } public void WritePort(byte[] send, int offSet, int count) { if (IsOpen) { serialPort.Write(send, offSet, count); } } } }