1、接收区清空内容按钮:btnClearReceived 保存数据按钮:btnSaveFile接收数据框:tbReceivedData 发送数据框:tbSendData自动发送:cbAutomaticSend 间隔时间:tbSpaceTime按16进制发送:cb16Send 发送区清空内容按钮:btnClearSend读入文件按钮:btnReadFile 发送按钮:btnSend2 创建一个方法类按Ctrl+shift+A快捷键创建一个类,名字叫Methods,代码为:using System;using System.Collections;using System.Collections.Ge
2、neric;using System.IO.Ports;using System.Linq;using System.Text;using System.Threading.Tasks;namespace 串口助手sdd class Methods /获取有效的COM口 public static string ActivePorts() ArrayList activePorts = new ArrayList(); foreach (string pname in SerialPort.GetPortNames() activePorts.Add(Convert.ToInt32(pname
3、.Substring(3); activePorts.Sort(); string mystr = new stringactivePorts.Count; int i = 0; foreach (int num in activePorts) mystri+ = COM + num.ToString(); return mystr; /16进制字符串转换为byte字符数组 public static Byte _16strToHex(string strValues) string hexValuesSplit = strValues.Split( ); Byte hexValues = n
4、ew BytehexValuesSplit.Length; Console.WriteLine(hexValuesSplit.Length); for (int i = 0; i hexValuesSplit.Length; i+) hexValuesi = Convert.ToByte(hexValuesSpliti, 16); return hexValues; /byte数组以16进制形式转字符串 public static string ByteTo16Str(byte bytes) string recData = null;/创建接收数据的字符串 foreach (byte out
5、Byte in bytes)/将字节数组以16进制形式遍历到一个字符串内 recData += outByte.ToString(X2) + ; return recData; /16进制字符串转换字符串 public static string _16strToStr(string _16str) string outStr = null; byte streamByte = _16strToHex(_16str); outStr = Encoding.Default.GetString(streamByte); return outStr; 2 Form1.cs的代码为:using Sys
6、tem.ComponentModel;using System.Data;using System.Drawing;using System.Text.RegularExpressions;using System.Windows.Forms;using System.IO; public partial class Form1 : Form /声明变量 SerialPort sp = new SerialPort(); bool isSetProperty = false;/串口属性设置标志位 private enum PortState/声明接口显示状态,枚举型 打开, 关闭 string
7、 path = AppDomain.CurrentDomain.BaseDirectory + confing.ini/声明配置文件路径 string tbSendDataStr = /发送窗口字符串存储 string tbSendData16 = /发送窗口16进制存储 List receivedDatas = new List();/接收数据泛型数组 /接收串口数据 private void sp_DataReceived(object sender, SerialDataReceivedEventArgs e) byte ReceivedData = new bytesp.BytesTo
8、Read;/创建接收字节数组 sp.Read(ReceivedData, 0, ReceivedData.Length);/读取所接收到的数据 receivedDatas.AddRange(ReceivedData); tbReceivedCount.Text = (Convert.ToInt32(tbReceivedCount.Text) + ReceivedData.Length).ToString(); if (cb16Display.Checked) tbReceivedData.Text = Methods.ByteTo16Str(receivedDatas.ToArray(); e
9、lse tbReceivedData.Text = Encoding.Default.GetString(receivedDatas.ToArray(); sp.DiscardInBuffer();/丢弃接收缓冲区数据 /发送串口数据 private void DataSend() try if (cb16Send.Checked) byte hexBytes = Methods._16strToHex(tbSendData16); sp.Write(hexBytes, 0, hexBytes.Length); tbSendCount.Text = (Convert.ToInt32(tbSen
10、dCount.Text) + hexBytes.Length).ToString(); sp.WriteLine(tbSendDataStr); tbSendCount.Text = (Convert.ToInt32(tbSendCount.Text) + tbSendDataStr.Length).ToString(); catch (Exception ex) MessageBox.Show(ex.Message.ToString(); return; /设置串口属性 private void SetPortProperty() sp.PortName = cbxCOMPort.Text.
11、Trim();/设置串口名 sp.BaudRate = Convert.ToInt32(cbxBaudRate.Text.Trim();/设置波特率 switch (cbxStopBits.Text.Trim()/设置停止位 case 1: sp.StopBits = StopBits.One; break;1.5 sp.StopBits = StopBits.OnePointFive;2 sp.StopBits = StopBits.Two; default: sp.StopBits = StopBits.None; sp.DataBits = Convert.ToInt32(cbxData
12、Bits.Text.Trim();/设置数据位 switch (cbxParity.Text.Trim()/设置奇偶校验位 无 sp.Parity = Parity.None;奇校验 sp.Parity = Parity.Odd;偶校验 sp.Parity = Parity.Even; sp.ReadTimeout = 5000;/设置超时时间为5s Control.CheckForIllegalCrossThreadCalls = false;/这个类中我们不检查跨线程的调用是否合法(因为.net 2.0以后加强了安全机制,,不允许在winform中直接跨线程访问控件的属性) /定义Data
13、Received事件的委托,当串口收到数据后出发事件 sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived); /设置端口显示状态 private void DisplayPortState(PortState portState) toolStripStatusLabel1.Text = cbxCOMPort.Text + 端口 处于 + portState + 状态 + cbxBaudRate.Text + + cbxDataBits.Text + + cbxStopBits.Text + + cbxPa
14、rity.Text; /重新打开串口 private void AgainOpenPort() if (sp.IsOpen) sp.Close(); SetPortProperty(); isSetProperty = true; sp.Open(); catch (Exception) isSetProperty = false; btnOpenCom.Text = 打开串口 DisplayPortState(PortState.关闭); MessageBox.Show(串口无效或已被占用!, 错误提示 DisplayPortState(PortState.打开); public Form1
15、() InitializeComponent(); /软件启动时加载事件 private void Form1_Load(object sender, EventArgs e) #region 加载配置文件 Hashtable ht = new Hashtable(); if (File.Exists(path) string myline = string str = new string2; using (StreamReader sr = new StreamReader(path) myline = sr.ReadLine(); while (myline != null) str =
16、 myline.Split(= ht.Add(str0, str1); catch(Exception ex) #endregion #region 设置窗口为固定大小且不可最大化 this.MaximumSize = this.Size; this.MinimumSize = this.Size; this.MaximizeBox = false; #region 列出常用的波特率 cbxBaudRate.Items.Add(12002400480096001920038400430005600057600115200 if (ht.ContainsKey(cbxBaudRate) cbxB
17、audRate.SelectedIndex = cbxBaudRate.Items.IndexOf(ht.ToString(); cbxBaudRate.SelectedIndex = 3; cbxBaudRate.DropDownStyle = ComboBoxStyle.DropDownList; #region 列出停止位 cbxStopBits.Items.Add(cbxStopBits cbxStopBits.SelectedIndex = cbxStopBits.Items.IndexOf(ht cbxStopBits.SelectedIndex = 0; cbxStopBits.
18、DropDownStyle = ComboBoxStyle.DropDownList; #region 列出数据位 cbxDataBits.Items.Add(8765cbxDataBits cbxDataBits.SelectedIndex = cbxDataBits.Items.IndexOf(ht cbxDataBits.SelectedIndex = 0; cbxDataBits.DropDownStyle = ComboBoxStyle.DropDownList; #region 列出奇偶校验位 cbxParity.Items.Add(cbxParity cbxParity.Sele
19、ctedIndex = cbxParity.Items.IndexOf(ht cbxParity.SelectedIndex = 0; cbxParity.DropDownStyle = ComboBoxStyle.DropDownList; #region COM口重新加载 cbxCOMPort.Items.Clear();/清除当前串口号中的所有串口名称 cbxCOMPort.Items.AddRange(Methods.ActivePorts();cbxCOMPort) & cbxCOMPort.Items.Contains(ht.ToString() cbxCOMPort.Select
20、edIndex = cbxCOMPort.Items.IndexOf(ht cbxCOMPort.SelectedIndex = 0; cbxCOMPort.DropDownStyle = ComboBoxStyle.DropDownList; #region 初始化计数器 tbSendCount.Text = 0 tbSendCount.ReadOnly = true; tbReceivedCount.Text = tbReceivedCount.ReadOnly = true; #region 初始化当前时间 toolStripStatusLabel3.Text = DateTime.No
21、w.ToString(); #region 初始化串口状态 toolStripStatusLabel1.ForeColor = Color.Blue; if (!isSetProperty)/串口未设置则设置串口属性关闭串口 /串口打开失败后,串口属性设置标志位设为false #region 初始化间隔时间tbSpaceTime tbSpaceTime.Text = ht.ToString(); tbSpaceTime.Text = 1000 #region 初始化按16进制显示状态cb16Display ht.ToString() = True) cb16Display.Checked = true; cb16Display.Checked = false; #region 初始化按16进制发送状态cb16Send cb16Send.Checked = true; cb16Send.Checked = false; #region 初始化发送区文本 if(ht.ContainsKey(tbSendData16 ht.ContainsKey(tbSendDataStr tbSendData16 = ht tbSendDataStr = ht tbSendData.Text = ht tbSendData.Focus(); /显
copyright@ 2008-2023 冰点文库 网站版权所有
经营许可证编号:鄂ICP备19020893号-2