一、界面:
主要代码如下:
(1)窗体加载
private void FrmMain_Load(object sender, EventArgs e)
{
try
{
cmbBTL.SelectedIndex = 6;
cmbDataBit.SelectedIndex = 0;
cmbJYBit.SelectedIndex = 0;
cmbStopBit.SelectedIndex = 0;
cmbDataType.SelectedIndex = 1;
ckShowRecData.Checked = true;
ckShowSendData.Checked = true;
for (int i = 0; i < 7; i++)
{
lstTs1[i] = new List<CANObj>();
}
debug_1_6[0] = "";
debug_1_6[1] = "";
debug_1_6[2] = "";
debug_1_6[3] = "";
debug_1_6[4] = "";
debug_1_6[5] = "";
debug_1_6[6] = "";
Thread thRec = new Thread(ShowReciData);
thRec.IsBackground = true;
thRec.Start();
Thread thSend = new Thread(ShowSendData);
thSend.IsBackground = true;
thSend.Start();
//Thread thR = new Thread(DataReceived);
//thR.IsBackground = true;
//thR.Start();
//Thread tBt = new Thread(SaveRecData);
//tBt.IsBackground = true;
//tBt.Start();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
(2)COM口加载:
private void cmbCOM_MouseClick(object sender, MouseEventArgs e)
{
try
{
cmbCOM.Items.Clear();
List<string> coms = new List<string>();
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_PnPEntity"))
{
var hardInfos = searcher.Get();
foreach (var hardInfo in hardInfos)
{
if (hardInfo.Properties["Name"].Value != null)
{
if (hardInfo.Properties["Name"].Value.ToString().Contains("COM"))
{
coms.Add(hardInfo.Properties["Name"].Value.ToString());
}
}
}
searcher.Dispose();
}
string[] portNames = coms.ToArray();
foreach (string portName in portNames)
{
ShowSendInfo(portName + "\r\n");
if (portName.Contains("COM"))
{
string com = portName.Substring(portName.IndexOf('(') + 1, portName.IndexOf(')') - portName.IndexOf('(') - 1);
string[] scoms = com.Replace("->", " ").Split(' ');
if (scoms.Length == 2)
{
cmbCOM.Items.Add(scoms[0]);
}
else
{
cmbCOM.Items.Add(com);
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
(3)打开串口:
SerialPort serialPort;
private void btnOpen_Click(object sender, EventArgs e)
{
try
{
if (btnOpen.Text == "打开串口")
{
string portName = cmbCOM.Text;
int baudRate = int.Parse(cmbBTL.Text);
int dataBits = int.Parse(cmbDataBit.Text);
float stopBit = float.Parse(cmbStopBit.Text);
string parity = cmbJYBit.Text;
ConnectSerialPort("", portName, baudRate, dataBits, stopBit, parity, ref serialPort);
if (serialPort != null && serialPort.IsOpen)
{
btnOpen.Text = "关闭串口";
btnOpen.BackColor = Color.Green;
lbLampStats.BackColor = Color.Green;
serialPort.DataReceived += Sp1_DataReceived;
}
}
else
{
btnOpen.Text = "打开串口";
btnOpen.BackColor = Color.White;
lbLampStats.BackColor = Color.LightGray;
if (serialPort != null)
{
serialPort.DataReceived -= Sp1_DataReceived;
serialPort.Dispose();
}
serialPort = null;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
(4)串口连接:
void ConnectSerialPort(string name, string portName, int baudRate, int dataBits, float stopBit, string parity, ref SerialPort sp)
{
try
{
sp = new SerialPort();
sp.PortName = portName;
sp.BaudRate = baudRate;
sp.DataBits = dataBits;
if (stopBit == 1)
{
sp.StopBits = StopBits.One;
}
else if (stopBit == 1.5)
{
sp.StopBits = StopBits.OnePointFive;
}
else if (stopBit == 2)
{
sp.StopBits = StopBits.Two;
}
else
{
sp.StopBits = StopBits.One;
}
if (parity.CompareTo("None") == 0)
{
sp.Parity = Parity.None;
}
else if (parity.CompareTo("Odd") == 0)
{
sp.Parity = Parity.Odd;
}
else if (parity.CompareTo("Even") == 0)
{
sp.Parity = Parity.Even;
}
else
{
sp.Parity = Parity.None;
}
sp.ReadTimeout = -1; // 设置超时读取时间
sp.RtsEnable = true;
sp.ReceivedBytesThreshold = 1;
if (!sp.IsOpen)
{
sp.Open();
}
}
catch (Exception ex)
{
MessageBox.Show("串口设备,异常错误:" + ex.Message);
sp = null;
}
}
(5)串口事件接收:
void Sp1_DataReceived(object sender, SerialDataReceivedEventArgs arg)
{
try
{
System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
byte[] receivedData = new byte[serialPort.BytesToRead]; //创建接收字节数组
serialPort.Read(receivedData, 0, receivedData.Length); //读取数据
if (receivedData.Length > 0)
{
string strRec = "";
string dataType = "HEX";
cmbDataType.Invoke(new Action(() =>
{
dataType = cmbDataType.Text;
}));
if (dataType == "HEX")
{
for (int i = 0; i < receivedData.Length; i++) //窗体显示
{
strRec += receivedData[i].ToString("X2") + " "; //16进制显示
}
}
else
{
strRec = asciiEncoding.GetString(receivedData);
}
reciveCount += receivedData.Length;
if (hcRecData.Count < 500000)
{
string hcData = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fffffff") + "->" + strRec;
hcRecData.Add(hcData);
}
else
{
string hcData = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fffffff") + "->" + strRec;
hcRecData.RemoveAt(0);
hcRecData.Add(hcData);
}
//if (ckShowRecData.Checked)
//{
// ShowSendInfo(strRec);
//}
}
}
catch (Exception ex)
{
}
}
结尾:代码太多,没有一一列出,感兴趣的伙伴可以到我上传的资源中下载源代码!!!