if (SerialPort.GetPortNames().Length == 0)
{
MessageBox.Show("没有检测到串口设备!");
}
else
{
port = GetAppConfig("ComPort");
SerialPortHelper.PortName = port;
SerialPortHelper.BaudRate = rate;
SerialPortHelper.StopBit = stop;
SerialPortHelper.RecieveDataEvent += new SerialPortHelper.RecieveData(RecieveData);
SerialPortHelper.Init();
SerialPortHelper.Start();
}
void RecieveData(byte[] data)
{
ASCIIEncoding encoding = new ASCIIEncoding();
string str = encoding.GetString(data);
if (!string.IsNullOrEmpty(str))
{
InsertData(str);
}
}
private void InsertData(string str)
{
try
{
lock (str)
{
if (str.Length < 32)
return;
//解析 并插入数据库
...
}
}
catch (Exception ex)
{
define.msg.Text = "解析数据" + ex.ToString();
define.log.Write(define.msg);
}
}
这是我以前项目的代码,你看看,希望对你有帮助