C#上位机——串口助手高级
using Microsoft.Win32;
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 串口助手
{public partial class Form1 : Form{private bool isOpen = false;//打开标志private bool isRxShow = true;//接收标志private List<byte> reciveBuffer = new List<byte>();//接收数据缓冲区private List<byte> sendBuffer = new List<byte>();//定义发送缓冲区private int reciveCount = 0;//计数接收到数据private int sendCount = 0;//计数发送出的数据//SerialPortpublic Form1(){InitializeComponent();Control.CheckForIllegalCrossThreadCalls = false;}private void Form1_Load(object sender, EventArgs e){//在设计页面已经预先添加了COM1 COM2 COM3 //this.port_cbb.Items.Add("COM4");//this.port_cbb.Items.Add("COM5");//this.port_cbb.SelectedIndex = 2;//this.baud_cbb.SelectedIndex = 1;//this.check_cbb.SelectedIndex = 0;//this.databit_cbb.SelectedIndex = 3;//this.stopbit_cbb.SelectedIndex = 0;// 给发送框添加预设文本// this.send_rtb.Text = "我是发送框";// 给接收框添加预设文本// this.recive_rtb.Text = "我是接收框";serialLoad();//加载串口的属性}//自动加载串口端口号private void serialLoad(){EncodingInfo[] encodingInfos = Encoding.GetEncodings();//支持的字符编码RegistryKey keyCom = Registry.LocalMachine.OpenSubKey(@"Hardware\DeviceMap\SerialComm");string[] sSubKeys = keyCom.GetValueNames();port_cbb.Items.Clear();foreach (var sValue in sSubKeys){string portName = (string)keyCom.GetValue(sValue);port_cbb.Items.Add(portName);}this.port_cbb.SelectedIndex = 0;this.baud_cbb.SelectedIndex = 1;this.check_cbb.SelectedIndex = 0;this.databit_cbb.SelectedIndex = 3;this.stopbit_cbb.SelectedIndex = 0;}//发送数据private void sendData(){serialPort1.Write(sendBuffer.ToArray(),0,sendBuffer.Count);sendCount += sendBuffer.Count;recivecount_tssl.Text = sendCount.ToString();}private void send_btn_Click(object sender, EventArgs e){// 如果发送的数据不为空,则接收if (this.send_rtb.Text != "" && serialPort1.IsOpen){Console.WriteLine(Transform.ToHexString(sendBuffer.ToArray()));sendData();}else{MessageBox.Show("请先输入发送数据!");}}private void open_btn_Click(object sender, EventArgs e){try{if (serialPort1.IsOpen == false){serialPort1.PortName = port_cbb.Text;serialPort1.BaudRate = Convert.ToInt32(baud_cbb.Text);serialPort1.DataBits = Convert.ToInt32(databit_cbb.Text);switch (check_cbb.SelectedIndex){// none odd even case 0:serialPort1.Parity = Parity.None;break;case 1:serialPort1.Parity = Parity.Odd;break;case 2:serialPort1.Parity = Parity.Even;break;default:serialPort1.Parity = Parity.None;break;}switch (stopbit_cbb.SelectedIndex){// 1 1.5 2case 0:serialPort1.StopBits = StopBits.One;break;case 1:serialPort1.StopBits = StopBits.OnePointFive;break;case 2:serialPort1.StopBits = StopBits.Two;break;default:serialPort1.StopBits = StopBits.One;break;}serialPort1.Open();isOpen = true;open_btn.Text = "关闭串口";}else{serialPort1.Close();isOpen = false;open_btn.Text = "打开串口";}}catch (Exception ex){MessageBox.Show(ex.ToString()+serialPort1.PortName.ToString());}}private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e){if (isRxShow == false) return;// 1,需要读取有效的数据 BytesToReadbyte[] dataTemp = new byte[serialPort1.BytesToRead];//将串口中的数据读出来serialPort1.Read(dataTemp,0,dataTemp.Length);//0表示偏移地址,dataTemp.Length表示数据长度reciveBuffer.AddRange(dataTemp);//将数据缓存到buff中reciveCount += dataTemp.Length;//进行接收计数//将buff中的数据更新到页面中,异步线程,更新UIthis.Invoke(new EventHandler(delegate{// 显示接收数据的长度recivecount_tssl.Text = reciveCount.ToString();if (!recivehex_chb.Checked)//如果没有选中{// 2, 编码格式的选择string str = Encoding.GetEncoding("gb2312").GetString(dataTemp);//gb2312编码格式来接收数据// 3,0x00 -> \0 结束 不会显示str =str.Replace("\0", "\\0");//发送00时,转译为\0recive_rtb.AppendText(str);// recive_rtb.AppendText(Encoding.GetEncoding("gb2312").GetString(dataTemp).Replace("\0", "\\0"));}else{// 十六进制是选中的状态下recive_rtb.AppendText(Transform.ToHexString(dataTemp, " "));}}));}private void stop_btn_Click(object sender, EventArgs e){if (isRxShow == true){isRxShow = false;stop_btn.Text = "取消暂停";}else{isRxShow = true;stop_btn.Text = "暂停";}}private void recivehex_chb_CheckedChanged(object sender, EventArgs e){if (recive_rtb.Text == "") return;if (recivehex_chb.Checked){recive_rtb.Text = Transform.ToHexString(reciveBuffer.ToArray()," ");//以十六进制的形式显示出来}else{recive_rtb.Text = Encoding.GetEncoding("gb2312").GetString(reciveBuffer.ToArray()).Replace("\0","\\0");//以字符串的形式显示出来}}private void clear_btn_Click(object sender, EventArgs e){reciveBuffer.Clear();recivecount_tssl.Text = "";recive_rtb.Text = "";}private void autoclear_chb_CheckedChanged(object sender, EventArgs e){if (autoclear_chb.Checked){timer1.Start();}else{timer1.Stop();}}private void timer1_Tick(object sender, EventArgs e){if (recive_rtb.Text.Length > 4096){reciveBuffer.Clear();recive_rtb.Text = "";recivecount_tssl.Text = "";}}private void send_rtb_Leave(object sender, EventArgs e){if (sendhex_chb.CheckState == CheckState.Checked){if (DataEncoding.IsHexString(send_rtb.Text.Replace(" ", ""))){sendBuffer.Clear();sendBuffer.AddRange(Transform.ToBytes(send_rtb.Text.Replace(" ", "")));}else{MessageBox.Show("请输入正确的十六进制数据!!");send_rtb.Select();}}else{sendBuffer.Clear();sendBuffer.AddRange(Encoding.GetEncoding("gb2312").GetBytes(send_rtb.Text));}}private void send_rtb_TextChanged(object sender, EventArgs e){// 十六进制切换 会出现问题 这问题就是0x00 转换}private void sendhex_chb_CheckedChanged(object sender, EventArgs e){if (send_rtb.Text == "") return;if (sendhex_chb.Checked == true){send_rtb.Text = Transform.ToHexString(sendBuffer.ToArray(), " ");//每一个字符以空格的形式隔开}else { send_rtb.Text = Encoding.GetEncoding("gb2312").GetString(sendBuffer.ToArray()).Replace("\0","\\0");}}private void sendclear_btn_Click(object sender, EventArgs e){sendBuffer.Clear();send_rtb.Text = "";sendCount = 0;recivecount_tssl.Text = "0";}}
}