最近写了个简单的串口接收GPS数据的程序,下面主程序中的代码,主要利用BackGroundWork组件来实现数据的接收。
using
System;
using
System.Collections.Generic;
using
System.ComponentModel;
using
System.Data;
using
System.Drawing;
using
System.Text;
using
System.Windows.Forms;
using
System.IO;
using
Microsoft.Practices.EnterpriseLibrary.Data;
using
Microsoft.Practices.EnterpriseLibrary.Data.Sql;
using
System.Data.Common;
using
System.Collections;

namespace
GPSSerialPortData

...
...
{
public partial class MainFrom : Form

......{
private System.IO.Ports.SerialPort[] ports = null;
private bool IsShowData = false;
StringBuilder f_SB = new StringBuilder();

public MainFrom()

......{
InitializeComponent();
}

private string newline()

......{
return " ";
}


/**//**//**//// <summary>
/// 打开串口并开始数据接收
/// </summary>
private void OpenPort()

......{
for (int i = 0; i < SerialPortConfig.Ports.Count; i++)

......{
try

......{
ports[i].Open();
ports[i].DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(SPort_DataReceived);
tbPortState.Text += "串口" + ports[i].PortName + "已经打开" + newline();
}
catch

......{
tbPortState.Text += "串口" + ports[i].PortName + "不存在或已占用" + newline();
}
}
}


/**//**//**//// <summary>
/// 停止数据接收并关闭串口
/// </summary>
private void ClosePort()

......{
for (int i = 0; i < SerialPortConfig.Ports.Count; i++)

......{
try

......{
if (ports[i].IsOpen)

......{
ports[i].DataReceived -= new System.IO.Ports.SerialDataReceivedEventHandler(SPort_DataReceived);
ports[i].Close();
}
tbPortState.Text += "串口" + ports[i].PortName + "已经关闭" + newline();
}
catch

......{
tbPortState.Text += "串口" + ports[i].PortName + "不存在或已占用" + newline();
}
}
}
private void AddReceiveData(byte[] bytes)

......{
lock (f_SB)

......{
foreach (byte b in bytes)

......{
if (b < 16)

......{
f_SB.Append( "0"+Convert.ToString(b, 16).ToUpper());
}
else

......{
f_SB.Append(Convert.ToString(b, 16).ToUpper());
}
}
}
}
BackgroundWorker f_BG = new BackgroundWorker();
private void bgWorkerAnalyze_DoWork(object sender, DoWorkEventArgs e)

......



















































































































