本人原创作品 希望提供给大家学习 共同学习 共同进步
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.Ports; using System.Threading; namespace SerialPortDebuggingTools { public partial class SerialPortDebugging : Form { public SerialPortDebugging() { InitializeComponent(); } public byte[] recb; delegate void SetTextCallback(string text, int count); public bool song16jinz = false; /// <summary> /// 代理方法给UI输出值 /// </summary> /// <param name="text"></param> private void SetText(string text, int count) { if (this.richTextBoxjieshou.InvokeRequired) { SetTextCallback d = new SetTextCallback(SetText); this.Invoke(d, new object[] { text, count }); } else { if (this.checkBoxenter.Checked) { RemoveText(); this.richTextBoxjieshou.AppendText(text + "\r\n"); } else { RemoveText(); this.richTextBoxjieshou.AppendText(text); } textBoxRx.Text = string.Format("RX:{0}", JShou(count)); } } public void RemoveText() { int count=richTextBoxjieshou.Lines.Length; if (count>=18) { richTextBoxjieshou.Text = ""; } } /// <summary> /// 打开串口或者关闭串口 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void butCorO_Click(object sender, EventArgs e) { if (SerialProtTools.IsOpen) { if (!this.checkBoxzhouqi.Checked) { SerialProtTools.Close(); this.butCorO.Text = "打开串口"; this.pictureBoxEnabled.Image = global::SerialPortDebuggingTools.Properties.Resources.colse; this.textBoxstatus.Text = SerialProtTools.PortName + " COLSED," + SerialProtTools.BaudRate + "," + this.comboBoxJyw.Text + "," + SerialProtTools.DataBits + "," + this.comboBoxTzw.Text; } else { MessageBox.Show("请先关闭自动发送才能关闭串口", "温馨提示!", MessageBoxButtons.OK, MessageBoxIcon.Hand); } } else { try { SerialProtTools.Open(); this.butCorO.Text = "关闭串口"; this.pictureBoxEnabled.Image = global::SerialPortDebuggingTools.Properties.Resources.open; this.textBoxstatus.Text = SerialProtTools.PortName + " OPENED," + SerialProtTools.BaudRate + "," + this.comboBoxJyw.Text + "," + SerialProtTools.DataBits + "," + this.comboBoxTzw.Text; } catch (Exception ex) { MessageBox.Show(ex.Message, "温馨提示!", MessageBoxButtons.OK, MessageBoxIcon.Hand); this.butCorO.Text = "打开串口"; this.pictureBoxEnabled.Image = global::SerialPortDebuggingTools.Properties.Resources.colse; this.textBoxstatus.Text = SerialProtTools.PortName + " COLSED," + SerialProtTools.BaudRate + "," + this.comboBoxJyw.Text + "," + SerialProtTools.DataBits + "," + this.comboBoxTzw.Text; } } } /// <summary> /// 初始化串口 /// </summary> public void initSerialProt() { bool YmY = false; string[] ports = SerialPort.GetPortNames(); foreach (string port in ports) { this.comboBoxserialPort.Items.Add(port); YmY = true; } if (YmY) { this.comboBoxserialPort.SelectedIndex = 0; } } /// <summary> /// 初始化所有串口相关的列 /// </summary> public void initAll() { this.comboBoxbtv.SelectedItem = "9600"; this.comboBoxJyw.SelectedItem = "NONE"; this.comboBoxSjw.SelectedItem = "8"; this.comboBoxTzw.SelectedItem = "1"; } private void SerialPortDebugging_Load(object sender, EventArgs e) { initSerialProt(); initAll(); comboBoxserialPort_SelectionChangeCommitted(sender, e); } /// <summary> /// 配置串口的所有信息 /// </summary> /// <param name="SerPort">串口对象</param> /// <param name="SerialName">串口名称</param> /// <param name="SerialBtv">串口波特率4800,9600,14400,19200,38400,56000,57600,115200,128000,256000</param> /// <param name="SerialJyw">串口校验位NONE,ODD,EVEN</param> /// <param name="SerialSjw">串口数据位8,7,6</param> /// <param name="SerialTzw">串口停止位1,2</param> /// <returns></returns> public SerialPort ConfigProt(SerialPort SerPort, string SerialName, string SerialBtv, string SerialJyw, string SerialSjw, string SerialTzw) { if (SerialName != null && !SerialName.Equals("")) { SerPort.PortName = SerialName; } //波特率设置 switch (SerialBtv) { case "4800": SerPort.BaudRate = 4800; break; case "9600": SerPort.BaudRate = 9600; break; case "14400": SerPort.BaudRate = 14400; break; case "19200": SerPort.BaudRate = 19200; break; case "38400": SerPort.BaudRate = 38400; break; case "56000": SerPort.BaudRate = 56000; break; case "57600": SerPort.BaudRate = 57600; break; case "115200": SerPort.BaudRate = 115200; break; default: SerPort.BaudRate = 9600; break; } //设置校验位 switch (SerialJyw) { case "NONE": SerPort.Parity = System.IO.Ports.Parity.None; break; case "ODD": SerPort.Parity = System.IO.Ports.Parity.Odd; break; case "EVEN": SerPort.Parity = System.IO.Ports.Parity.Even; break; default: SerPort.Parity = System.IO.Ports.Parity.None; break; } //设置数据位 switch (SerialSjw) { case "8": SerPort.DataBits = 8; break; case "7": SerPort.DataBits = 7; break; case "6": SerPort.DataBits = 6; break; default: SerPort.DataBits = 8; break; } switch (SerialTzw) { case "1": SerPort.StopBits = System.IO.Ports.StopBits.One; break; case "2": SerPort.StopBits = System.IO.Ports.StopBits.Two; break; default: SerPort.StopBits = System.IO.Ports.StopBits.One; break; } return SerPort; } private void comboBoxserialPort_SelectionChangeCommitted(object sender, EventArgs e) { if (SerialProtTools.IsOpen) SerialProtTools.Close(); this.SerialProtTools = ConfigProt(this.SerialProtTools, this.comboBoxserialPort.Text, this.comboBoxbtv.Text, this.comboBoxJyw.Text, this.comboBoxSjw.Text, this.comboBoxTzw.Text); try { SerialProtTools.Open(); this.butCorO.Text = "关闭串口"; this.pictureBoxEnabled.Image = global::SerialPortDebuggingTools.Properties.Resources.open; if (SerialProtTools.IsOpen) { this.textBoxstatus.Text = SerialProtTools.PortName + " OPENED," + SerialProtTools.BaudRate + "," + this.comboBoxJyw.Text + "," + SerialProtTools.DataBits + "," + this.comboBoxTzw.Text; } } catch (Exception ex) { MessageBox.Show(ex.Message, "温馨提示!", MessageBoxButtons.OK, MessageBoxIcon.Hand); this.butCorO.Text = "打开串口"; this.checkBoxzhouqi.Checked = false; this.timerSong.Stop(); this.pictureBoxEnabled.Image = global::SerialPortDebuggingTools.Properties.Resources.colse; } } private void butcolsed_Click(object sender, EventArgs e) { try { this.timerSong.Stop(); Application.Exit(); } catch (Exception) { Application.Exit(); } finally { Application.Exit(); } } private void butqingkongjies_Click(object sender, EventArgs e) { richTextBoxjieshou.Text = ""; } private void butqingkongSong_Click(object sender, EventArgs e) { richTextBoxSong.Text = ""; } private void textBoxhangmiao_KeyPress(object sender, KeyPressEventArgs e) { this.checkBoxzhouqi.Checked = false; if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != 46) { e.Handled = true; } } private void butqingling_Click(object sender, EventArgs e) { textBoxRx.Text = "RX:0"; textBoxtx.Text = "TX:0"; } private void checkBox16jinz_CheckedChanged(object sender, EventArgs e) { if (checkBox16jinz.Checked) { song16jinz = true; checkBoxjieshou.Checked = true; string temp = this.richTextBoxSong.Text; temp = temp.Replace(" ", ""); if (delyichang(temp)) { this.richTextBoxSong.Text = ""; } } else { song16jinz = false; string temp = this.richTextBoxSong.Text; temp = temp.Replace(" ", ""); if (delyichang(temp)) { this.richTextBoxSong.Text = ""; } checkBoxjieshou.Checked = false; } } private void checkBoxjieshou_CheckedChanged(object sender, EventArgs e) { if (checkBoxjieshou.Checked) { song16jinz = true; checkBox16jinz.Checked = true; string temp = this.richTextBoxSong.Text; temp = temp.Replace(" ", ""); if (delyichang(temp)) { this.richTextBoxSong.Text = ""; } } else { song16jinz = false; string temp = this.richTextBoxSong.Text; temp = temp.Replace(" ", ""); if (delyichang(temp)) { this.richTextBoxSong.Text = ""; } checkBox16jinz.Checked = false; } } string jieshou = String.Empty; private void SerialProtTools_DataReceived(object sender, SerialDataReceivedEventArgs e) { if (SerialProtTools.IsOpen) { Thread.Sleep(100); if (song16jinz) { int n = SerialProtTools.BytesToRead; recb = new byte[n]; SerialProtTools.Read(recb, 0, recb.Length); if (recb != null && recb.Length > 0) { SetText(dispackage(recb), n); } } else { jieshou = SerialProtTools.ReadExisting(); if (jieshou != String.Empty) { SetText(jieshou, jieshou.Length); } } } } /// <summary> /// DIY方法的解析方法 /// </summary> /// <param name="reb"></param> /// <returns></returns> public string dispackage(byte[] reb) { string temp = ""; foreach (byte b in reb) temp += b.ToString("X2") + " "; return temp; } /// <summary> /// 16进制字符串转字节数组 /// </summary> /// <param name="hexString"></param> /// <returns></returns> private static byte[] strToToHexByte(string hexString) { hexString = hexString.Replace(" ", ""); if ((hexString.Length % 2) != 0) hexString += " "; byte[] returnBytes = new byte[hexString.Length / 2]; for (int i = 0; i < returnBytes.Length; i++) returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2).Trim(), 16); return returnBytes; } /// <summary> /// 发送信息 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void butshoudongsong_Click(object sender, EventArgs e) { SongSJ(); } public void SongSJ() { if (SerialProtTools.IsOpen) { //代发送的值 int i = 0; string liushu = this.richTextBoxSong.Text; if (liushu != null && !liushu.Equals("")) { if (song16jinz) { liushu = liushu.Replace(" ", ""); i = liushu.Length / 2; if (!delyichang(liushu)) { SerialProtTools.Write(strToToHexByte(liushu), 0, i); } } else { SerialProtTools.Encoding = Encoding.GetEncoding("GB2312"); i = liushu.Length; SerialProtTools.Write(liushu); } textBoxtx.Text = string.Format("TX:{0}", jiaFan(i)); } } else { this.timerSong.Stop(); MessageBox.Show("串口没打开请打开串口再操作", "温馨提示!", MessageBoxButtons.OK, MessageBoxIcon.Hand); } } public bool delyichang(string bigstr) { string jiache = "0123456789ABCDEF"; char[] charshuz = bigstr.ToCharArray(); for (int i = 0; i < charshuz.Length; i++) { char value = char.ToUpper(charshuz[i]); if (jiache.IndexOf(value) < 0) { return true; } } return false; } /// <summary> /// 接受计数 /// </summary> /// <param name="count"></param> /// <returns></returns> public int JShou(int count) { string temp = textBoxRx.Text; temp = temp.Replace("RX:", ""); try { int cc = Convert.ToInt32(temp); return (cc + count); } catch { return count; } } /// <summary> /// 发送计数 /// </summary> /// <param name="count"></param> /// <returns></returns> public int jiaFan(int count) { string temp = textBoxtx.Text; temp = temp.Replace("TX:", ""); try { int cc = Convert.ToInt32(temp); return (cc + count); } catch { return count; } } private void checkBoxzhouqi_CheckedChanged(object sender, EventArgs e) { string shijian = this.textBoxhangmiao.Text; if (checkBoxzhouqi.Checked) { if (shijian != null && !shijian.Equals("")) { int zhouq = Convert.ToInt32(shijian); if (zhouq > 0) { this.timerSong.Interval = zhouq; this.timerSong.Start(); } else { MessageBox.Show("自动发送周期必须大于0毫秒", "温馨提示!", MessageBoxButtons.OK, MessageBoxIcon.Hand); } } } else { this.timerSong.Stop(); } } private void timerSong_Tick(object sender, EventArgs e) { SongSJ(); } private void butBoxAuthor_Click(object sender, EventArgs e) { } } }