C#---串口调试助手

 

 

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 using System.Threading.Tasks;
  6 using System.Windows;
  7 using System.Windows.Controls;
  8 using System.Windows.Data;
  9 using System.Windows.Documents;
 10 using System.Windows.Input;
 11 using System.Windows.Media;
 12 using System.Windows.Media.Imaging;
 13 using System.Windows.Navigation;
 14 using System.Windows.Shapes;
 15 using System.IO.Ports;
 16 using System.Text;
 17 
 18 
 19 namespace SerialDebuggingWPF
 20 {
 21     /// <summary>
 22     /// MainWindow.xaml 的交互逻辑
 23     /// </summary>
 24     public partial class MainWindow : Window
 25     {
 26         private System.IO.Ports.SerialPort serialPort = new SerialPort();//串口对象
 27         private StringBuilder stringBuilder = new StringBuilder();//作为缓冲
 28         public MainWindow()
 29         {
 30             InitializeComponent();
 31         }
 32 
 33         /// <summary>
 34         /// 加载窗口
 35         /// </summary>
 36         /// <param name="sender"></param>
 37         /// <param name="e"></param>
 38 
 39         private void Window_Loaded(object sender, RoutedEventArgs e)
 40         {
 41             portname.ItemsSource = SerialPort.GetPortNames();
 42             if (portname.Items.Count > 0)
 43             {
 44                 this.portname.SelectedIndex = 0;
 45             }
 46             else
 47             {
 48                 MessageBox.Show("未找到有效串口!!", "提示");
 49             }
 50             //Console.WriteLine(this.baud.Items.IndexOf("9600")+"");
 51             this.baud.SelectedIndex = 1;
 52             this.jy.SelectedIndex = 0;
 53             this.jy_Copy.SelectedIndex = 0;
 54             this.SJ.SelectedIndex = 6;
 55 
 56         }
 57         /// <summary>
 58         /// 串口数据通信
 59         /// </summary>
 60         /// <param name="sender"></param>
 61         /// <param name="e"></param>
 62         private void DataReceived(object sender, SerialDataReceivedEventArgs e)
 63         {
 64             Byte[] receivedData = new Byte[serialPort.BytesToRead];//获取读取字节个数
 65             try
 66             {
 67                 serialPort.Read(receivedData, 0, receivedData.Length);
 68                 String info = Encoding.GetEncoding("GB2312").GetString(receivedData);
 69                 updateReceiveText("接收数据: " + info);
 70             }
 71             catch
 72             {
 73                 MessageBox.Show("串口失效", "提示");
 74                 serialPort.Close();
 75                 if (Connect.Dispatcher.CheckAccess())
 76                 {
 77                     Connect.Content = "打开串口";
 78                 }
 79                 else
 80                 {
 81                     Action act = () => { Connect.Content = "打开串口"; };
 82                     Connect.Dispatcher.Invoke(act);
 83                 }
 84             }
 85         }
 86 
 87 
 88 
 89 
 90 
 91 
 92 
 93         /// <summary>
 94         /// 串口连接按钮
 95         /// </summary>
 96         /// <param name="sender"></param>
 97         /// <param name="e"></param>
 98         private void Connect_Click(object sender, RoutedEventArgs e)
 99         {
100             if (serialPort.IsOpen)
101             {
102                 serialPort.Close();
103                 if (Connect.Dispatcher.CheckAccess())
104                 {
105                     Connect.Content = "打开串口";
106                 }
107                 else
108                 {
109                     Action act = () => { Connect.Content = "打开串口"; };
110                     Connect.Dispatcher.Invoke(act);
111                 }
112                 Console.WriteLine("正在关闭串口");
113             }
114             else
115             {
116                 if (portname.Text != null && !portname.Text.Equals(""))
117                 {
118                     serialPort.PortName = portname.SelectedItem.ToString();
119                     serialPort.BaudRate = Convert.ToInt32(baud.Text);
120                     try
121                     {
122                         serialPort.Open();//打开串口
123                         if (Connect.Dispatcher.CheckAccess())
124                         {
125                             Connect.Content = "关闭串口";
126                         }
127                         else
128                         {
129                             Action act = () => { Connect.Content = "关闭串口"; };
130                             Connect.Dispatcher.Invoke(act);
131                         }
132                         Console.WriteLine("正在打开串口");
133                         serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceived);//添加事件监听程序                        
134                     }
135                     catch
136                     {
137                         MessageBox.Show("该串口不存在或被占用,请确认", "提示");
138                     }
139                 }
140                 else
141                 {
142                     MessageBox.Show("请输入正确的串口号", "提示");
143                 }
144             }
145         }
146 
147 
148         /// <summary>
149         /// 数据发送按钮
150         /// </summary>
151         /// <param name="sender"></param>
152         /// <param name="e"></param>
153         private void Send_Click(object sender, RoutedEventArgs e)
154         {
155             String s = this.SendText.Text.Trim();
156             if (serialPort.IsOpen)
157             {
158                 if (s != null && !"".Equals(s))
159                 {
160                     try
161                     {
162                         byte[] Data = Encoding.UTF8.GetBytes(s);
163                         serialPort.Write(Data, 0, Data.Length);
164                         updateReceiveText("发送数据: " + s);
165                     }
166                     catch (Exception ex)
167                     {
168                         Console.WriteLine(ex.Message);
169                         MessageBox.Show("串口失效", "提示");
170                     }
171                 }
172                 else
173                 {
174                     Console.WriteLine("文本为空");
175                 }
176             }
177             else
178             {
179                 MessageBox.Show("请确认串口状态", "提示");
180             }
181         }
182 
183         private void updateReceiveText(string str)
184         {
185             if (ReceiveText.Dispatcher.CheckAccess())
186             {
187                 ReceiveText.AppendText(str + "\r\n");
188             }
189             else
190             {
191                 Action act = () => { ReceiveText.AppendText(str + "\r\n"); };
192                 ReceiveText.Dispatcher.Invoke(act);
193             }
194         }
195 
196         private void Connect_Copy_Click(object sender, RoutedEventArgs e)
197         {
198             this.ReceiveText.Clear();
199             this.SendText.Clear();
200         }
201 
202        
203     }
204     }
205 
206   
207     
  1 using System;
  2 using System.Collections.Generic;
  3 using System.IO.Ports;
  4 using System.Linq;
  5 using System.Text;
  6 using System.Threading.Tasks;
  7 
  8 namespace SerialDebuggingWPF
  9 {
 10     class MyConvert
 11     {
 12       
 13         
 14 
 15         public static byte[] strToToHexByte(string hexString)//16进制字符转字节数组
 16         {
 17             hexString = hexString.Replace(" ", "");
 18             if ((hexString.Length % 2) != 0)
 19                 hexString += " ";
 20             byte[] returnBytes = new byte[hexString.Length / 2];
 21             for (int i = 0; i < returnBytes.Length; i++)
 22                 returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
 23             return returnBytes;
 24         }
 25 
 26         public static String Byteto16String(byte b)//字节转16进制字符
 27         {
 28             String str = Convert.ToString(b, 16);
 29             if (str.Length == 1)
 30             {
 31                 str = "0" + str;
 32             }
 33             return str;
 34         }
 35 
 36         public static String Byteto16String(byte[] b)//字节数组转16进制字符
 37         {
 38             String s = "";
 39             foreach (byte date in b)
 40             {
 41                 String str = Convert.ToString(date, 16);
 42                 if (str.Length == 1)
 43                 {
 44                     str = "0" + str;
 45                 }
 46                 s = s + str;
 47             }
 48 
 49             return s;
 50         }
 51 
 52         public static String Byteto16String(byte[] b, int a)//具体长度字节数组转16进制字符
 53         {
 54             String s = "";
 55             for (int i = 0; i < a; i++)
 56             {
 57                 String str = Convert.ToString(b[i], 16);
 58                 if (str.Length == 1)
 59                 {
 60                     str = "0" + str;
 61                 }
 62                 s = s + str;
 63             }
 64 
 65             return s;
 66         }
 67 
 68         public static String Byteto16String(byte[] B, int a, int b)//指定长度字节数组转16进制字符
 69         {
 70             String s = "";
 71             for (int i = 0; i < b; i++, a++)
 72             {
 73                 String str = Convert.ToString(B[a], 16);
 74                 if (str.Length == 1)
 75                 {
 76                     str = "0" + str;
 77                 }
 78                 s = s + str;
 79             }
 80 
 81             return s;
 82         }
 83 
 84         //int i = Convert.ToInt32("10", 16);//将十六进制“10”转换为十进制i
 85 
 86         //string s = string.Format("{0:X}", i);//将十进制i转换为十六进制s
 87 
 88         public static String[] SubString(String Data)//切割字符串成字符数组
 89         {//14
 90             Data = Data.Replace(" ", "");
 91             String[] data = new String[Data.Length / 2];//7
 92             for (int x = 0, y = 0; x < data.Length; x++, y += 2)//0~6
 93             {
 94                 data[x] = Data.Substring(y, 2);
 95             }
 96             return data;
 97         }
 98 
 99         public static String SubString2(String Data)//修改字符串成两个一组加空格
100         {
101             String[] data = SubString(Data);
102             String s = "";
103             for (int i = 0; i < data.Length; i++)
104             {
105                 if (i < data.Length - 1)
106                 {
107                     s = s + data[i] + " ";
108                 }
109                 else
110                 {
111                     s = s + data[i];
112                 }
113             }
114             return s.ToUpper();
115         }
116 
117         public static String String_10toString_16(String s)//十进制字符转16进制字符
118         {
119             int a = Convert.ToInt32(s);
120             String ss = String.Format("{0:X}", a);
121             if (ss.Length == 1)
122             {
123                 ss = "0" + ss;
124             }
125             ss = ss.ToUpper();
126             return ss;
127         }
128 
129     }
130 }

 

posted on 2021-09-03 10:03  Bytezero!  阅读(465)  评论(0编辑  收藏  举报