C#开发的串口转发工具含源码
1、上图
2、主要代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Text;
using System.Windows.Forms;
namespace SerialPortUtil
{
public partial class FormMainFrame : Form
{
private SerialPort mSerialPortFrom = new SerialPort();
private SerialPort mSerialPortTo = new SerialPort();
private readonly object mLock = new object();
private delegate void InvokeCallBack();
private List<string> listStringFrom = new List<string>();
private List<string> listStringTo = new List<string>();
public FormMainFrame()
{
InitializeComponent();
SetStyle(ControlStyles.ResizeRedraw, true);
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
/*
mSerialPortFrom.BaudRate = 115200;
mSerialPortFrom.Parity = Parity.None;
mSerialPortFrom.StopBits = StopBits.One;
mSerialPortFrom.DataBits = 8;
mSerialPortTo.BaudRate = 115200;
mSerialPortTo.Parity = Parity.None;
mSerialPortTo.StopBits = StopBits.One;
mSerialPortTo.DataBits = 8;*/
buttonStop.Enabled = false;
mSerialPortFrom.DataReceived += ((s, e) =>
{
lock (mLock)
{
try
{
byte[] byteRead = new byte[mSerialPortFrom.BytesToRead];
if (byteRead.Length == 0)
return;
mSerialPortFrom.Read(byteRead, 0, byteRead.Length);
mSerialPortTo.Write(byteRead, 0, byteRead.Length);
string strHex = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
for (int i = 0; byteRead.Length > 0 && i < byteRead.Length; i++)
{
strHex += " " + byteRead[i].ToString("X2");
}
UpdateGridView(listStringTo, dataGridView2, strHex);
}
catch (Exception ex)
{
}
}
});
}
private void UpdateGridView(List<string> list, DataGridView dataGridView, string strHex)
{
list.Insert(0, strHex);
if (list.Count > 50)
{
list.RemoveAt(50);
}
this.BeginInvoke(new InvokeCallBack(() =>
{
for (int i = 0; i < list.Count; i++)
{
if (dataGridView.Rows.Count <= i)
{
dataGridView.Rows.Add();
}
dataGridView.Rows[i].Cells[0].Value = list[i];
}
dataGridView.AutoResizeColumns();
}));
}
private void Start()
{
Stop();
try
{
serialPortPanelFrom.ModifySerialPort(mSerialPortFrom);
serialPortPanelTo.ModifySerialPort(mSerialPortTo);
mSerialPortTo.Open();
mSerialPortFrom.Open();
buttonStart.Enabled = false;
buttonStop.Enabled = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace);
}
}
private void Stop()
{
try
{
mSerialPortTo.Close();
mSerialPortFrom.Close();
buttonStart.Enabled = true;
buttonStop.Enabled = false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace);
}
}
private void buttonStart_Click(object sender, EventArgs e)
{
Start();
}
private void buttonStop_Click(object sender, EventArgs e)
{
Stop();
}
}
}