C#串口助手,基于.Net5.0开发的WPF程序,实现串口通信功能,具有收发信息的设置,其中还包含WPF打包程序,无广告及开源。

特点:

1.自动查找并列出可用串口。

2.设置接受是否换行、显示发送内容、显示时间等设置。

3.可设置自动间隔时间去发送。

4.可切换Hex和String显示。

5.无附加依赖库。

接收核心代码:

private void SerialDataReceive(object sender, SerialDataReceivedEventArgs e)

{

int num = serialPort.BytesToRead;

byte[] buffer = new byte[num];

receiveCount += num;

serialPort.Read(buffer, 0, num);

ReceiveLength.Text = num.ToString();

string msg = "";

if (showTime == true)

{

msg += $"[{DateTime.Now.ToString("HH:mm:ss.fff")}] ";

}

if (receiveFormat.Equals("Hex"))

{

foreach (byte b in buffer)

{

msg += $"{b.ToString("X2")} ";

}

}else if (receiveFormat.Equals("ASCII"))

{

msg += $"{Encoding.ASCII.GetString(buffer)} ";

}

message.Append(msg);

if(autoWrap == true)

{

message.Append("\r\n");

}

try

{

this.Dispatcher.Invoke(new Action(() =>

{

MessageReceive.Text = message.ToString();

}));

}catch(Exception ex)

{

}

}

发送核心代码:

private void SendMsg_Click(object sender, RoutedEventArgs e)

{

byte[] data;

if (serialPort.IsOpen)

{

string msg = MessageSend.Text.ToString();

if (!string.IsNullOrWhiteSpace(msg))

{

try

{

if (sendFormat.Equals("ASCII"))

{

serialPort.Write(msg);

HandleSendFormat(msg, "ASCII");

currentSendMsgASCII = msg;

if (ComboBoxSendRecord.Items.Count == 0 || !ComboBoxSendRecord.Items.Contains(msg))

{

ComboBoxSendRecord.Items.Insert(0, msg);

ComboBoxSendRecord.SelectedIndex = 0;

}

SendLength.Text = Encoding.Default.GetBytes(msg).Length.ToString();

}

else if (sendFormat.Equals("Hex"))

{

string pattern = @"\s";

string relacement = "";

Regex rgx = new Regex(pattern);

string msg1 = rgx.Replace(msg, relacement);

int len = Convert.ToInt32(Math.Ceiling((double)msg1.Length / 2));

data = new byte[len];

for (int i = 0; i < data.Length; i++)

{

int s = 0;

try

{

s = Convert.ToInt32(msg1.Substring(i * 2, 2), 16);

}catch(Exception ex)

{

s = Convert.ToInt32(msg1.Substring(i * 2, 1) + "0", 16);

}

data[i] = Convert.ToByte(s);

}

serialPort.Write(data, 0, data.Length);

HandleSendFormat(msg1, "Hex");

currentSendMsgHexStr = msg1;

currentSendMsgHex = data;

if (ComboBoxSendRecord.Items.Count == 0 || !ComboBoxSendRecord.Items.Contains(msg1))

{

ComboBoxSendRecord.Items.Insert(0, msg1);

ComboBoxSendRecord.SelectedIndex = 0;

}

SendLength.Text = data.Length.ToString();

}

if(autoReSend == true)

{

if (reSendTime > 0)

{

mainTimer.Interval = reSendTime;

mainTimer.Start();

}

else

{

MessageBox.Show("自动重发时间需大于0ms");

}

}

}

catch(Exception ex)

{

MessageBox.Show(ex.Message);

}

}

}

else

{

MessageBox.Show("请先打开串口");

}

}

备注:

(GitHub地址:https://github.com/superleej/SerialAssistant) (GitHub克隆库:https://github.com/superleej/SerialAssistant.git) 其中含有的将WPF打包成安装程序的项目,但鉴于各人电脑文件位置设置的不一样,不能保证这个打包项目一定能跑起来,需要帮助可以联系我。 因为是一路学习摸索地去开发,有不好的地方或者建议,欢迎大家提出了,我虚心接受学习。

好文链接

评论可见,请评论后查看内容,谢谢!!!评论后请刷新页面。