前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >第一个WPF程序(串口调试)

第一个WPF程序(串口调试)

作者头像
CNXY
发布2020-02-18 14:01:38
9380
发布2020-02-18 14:01:38
举报
文章被收录于专栏:C# 编程

本例子仅支持“ASCII”编码的串口数据发送与接收,如果需要其他编码,请自行更改,谢谢!

界面代码如下:

代码语言:javascript
复制
 1 <Window x:Class="SerialPortDebug.MainWindow"
 2         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 3         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 4         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
 5         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
 6         xmlns:local="clr-namespace:SerialPortDebug"
 7         mc:Ignorable="d"
 8         Title="串口调试助手 - ASCII" Height="450" Width="800" WindowStartupLocation="CenterScreen" Loaded="Window_Loaded">
 9     <Grid Margin="0,0,0,0.5">
10         <Grid.RowDefinitions>
11             <RowDefinition Height="292*"/>
12             <RowDefinition Height="131*"/>
13         </Grid.RowDefinitions>
14         <Grid.ColumnDefinitions>
15             <ColumnDefinition Width="236"/>
16             <ColumnDefinition/>
17         </Grid.ColumnDefinitions>
18         <GroupBox Header="配置" Margin="10" Grid.RowSpan="2">
19             <Grid >
20                 <Grid.ColumnDefinitions>
21                     <ColumnDefinition Width="83"/>
22                     <ColumnDefinition Width="121"/>
23                 </Grid.ColumnDefinitions>
24                 <Grid.RowDefinitions>
25                     <RowDefinition Height="30"/>
26                     <RowDefinition Height="30"/>
27                     <RowDefinition Height="30"/>
28                     <RowDefinition Height="30"/>
29                     <RowDefinition Height="30"/>
30                     <RowDefinition Height="30"/>
31                     <RowDefinition Height="30"/>
32                     <RowDefinition Height="14"/>
33                     <RowDefinition/>
34                 </Grid.RowDefinitions>
35                 <Label Name="label1" Content="端口" Margin="37,2,9,2" VerticalAlignment="Center" Height="26" HorizontalContentAlignment="Right"/>
36                 <Label Name="label2" Content="波特率" Margin="0,2,10,2" VerticalAlignment="Center" Height="26" Width="54" Grid.Row="1" HorizontalAlignment="Right" HorizontalContentAlignment="Right"/>
37                 <Label Name="label3" Content="奇偶校验位" HorizontalAlignment="Right" Margin="0,2,10,2" VerticalAlignment="Center" Height="26" Width="71" Grid.Row="2" HorizontalContentAlignment="Right"/>
38                 <Label Name="label4" Content="停止位" HorizontalAlignment="Right" Margin="0,2,10,2" VerticalAlignment="Center" Height="26" Width="54" Grid.Row="3" HorizontalContentAlignment="Right"/>
39                 <Label Name="label5" Content="数据位" HorizontalAlignment="Right" Margin="0,4,10,2" VerticalAlignment="Center" Height="24" Width="54" Grid.Row="4" HorizontalContentAlignment="Right"/>
40                 <Label  Name="label6" Content="流控制" HorizontalAlignment="Right" VerticalAlignment="Center" Height="25" Width="54" Grid.Row="5" Margin="0,3,10,2" HorizontalContentAlignment="Right"/>
41                 <Label  Name="label7" Content="超时(ms)" HorizontalAlignment="Right" VerticalAlignment="Center" Height="26" Width="61" Grid.Row="6" Margin="0,2,10,2" HorizontalContentAlignment="Right"/>
42                 <ComboBox Name="comboBox1" Grid.Column="1" Margin="15,4,18,4" VerticalAlignment="Center" Height="22"/>
43                 <ComboBox Name="comboBox2" Grid.Column="1" Margin="15,4,18,4" VerticalAlignment="Center" Height="22" Grid.Row="1"/>
44                 <ComboBox Name="comboBox3" Grid.Column="1" Margin="15,4,18,4" VerticalAlignment="Center" Height="22" Grid.Row="2"/>
45                 <ComboBox Name="comboBox4" Grid.Column="1" Margin="15,4,18,4" VerticalAlignment="Center" Height="22" Grid.Row="3"/>
46                 <ComboBox Name="comboBox5" Grid.Column="1" Margin="15,4,18,4" VerticalAlignment="Center" Height="22" Grid.Row="4"/>
47                 <ComboBox Name="comboBox6" Grid.Column="1" Margin="15,4,18,4" VerticalAlignment="Center" Height="22" Grid.Row="5"/>
48                 <TextBox Name="textBox1" Grid.Column="1" Height="22" Margin="15,4,18,4" Grid.Row="6" TextWrapping="Wrap" Text="2000" VerticalAlignment="Center"/>
49                 <Button Name="button1" Content="开启" Grid.Column="1" Margin="15,10,18,0" Grid.Row="8" VerticalAlignment="Top" Height="26" Click="button1_Click"/>
50             </Grid>
51         </GroupBox>
52         <GroupBox Name="groupBox1" Grid.Column="1" Header="接收区" Margin="10,5,10,14.5">
53             <Grid >
54                 <Grid.RowDefinitions>
55                     <RowDefinition Height="5*"/>
56                     <RowDefinition Height="246*"/>
57                 </Grid.RowDefinitions>
58                 <Grid.ColumnDefinitions>
59                     <ColumnDefinition/>
60                 </Grid.ColumnDefinitions>
61                 <TextBox Name="textBox2" Margin="10,5,10,10" Grid.Row="1" TextWrapping="Wrap" Text="TextBox"/>
62             </Grid>
63         </GroupBox>
64         <GroupBox Name="groupBox2" Grid.Column="1" Header="发送区" Margin="10,0.5,10,10" Grid.Row="1">
65             <Grid>
66                 <Grid.ColumnDefinitions>
67                     <ColumnDefinition Width="317*"/>
68                     <ColumnDefinition Width="70"/>
69                     <ColumnDefinition Width="80"/>
70                     <ColumnDefinition Width="80"/>
71                 </Grid.ColumnDefinitions>
72                 <Grid.RowDefinitions>
73                     <RowDefinition/>
74                     <RowDefinition Height="23"/>
75                 </Grid.RowDefinitions>
76                 <TextBox Name="textBox3" Margin="10,10,6,10" TextWrapping="Wrap" Text="TextBox" Grid.ColumnSpan="4"/>
77                 <Button x:Name="button2" Content="回车发送" Grid.Column="2" HorizontalAlignment="Center" Margin="0" Grid.Row="1" VerticalAlignment="Center" Width="70" Height="19" Click="button2_Click"/>
78                 <Button Name="button3" Content="直接发送" Grid.Column="3" HorizontalAlignment="Center" Margin="5,2" Grid.Row="1" VerticalAlignment="Center" Width="70" Height="19" Click="button3_Click"/>
79 
80             </Grid>
81         </GroupBox>
82 
83     </Grid>
84 </Window>

如下图:

后台代码:

代码语言:javascript
复制
  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 using System.Windows;
  6 using System.Windows.Controls;
  7 using System.Windows.Data;
  8 using System.Windows.Documents;
  9 using System.Windows.Input;
 10 using System.Windows.Media;
 11 using System.Windows.Media.Imaging;
 12 using System.Windows.Navigation;
 13 using System.Windows.Shapes;
 14 using System.IO.Ports;
 15 using System.Threading;
 16 
 17 namespace SerialPortDebug
 18 {
 19     /// <summary>
 20     /// MainWindow.xaml 的交互逻辑
 21     /// </summary>
 22     public partial class MainWindow : Window
 23     {
 24         public MainWindow()
 25         {
 26             InitializeComponent();
 27         }
 28        
 29         private void EnableReceiveAndSendGroup(bool isFirstLoad, bool enable)
 30         {
 31             groupBox1.IsEnabled = enable;
 32             if (isFirstLoad)
 33             {
 34                 textBox2.IsEnabled = false;
 35                 textBox2.Clear();
 36             }
 37             groupBox2.IsEnabled = enable;
 38             if (!textBox3.IsEnabled) textBox3.Clear();
 39         }
 40 
 41         private void LoadParameters()
 42         {
 43             EnableReceiveAndSendGroup(true,false);
 44             button1.IsEnabled = false;
 45             comboBox1.ItemsSource = SerialPortHelper.GetSerialPorts();
 46             if (comboBox1.Items.Count == 0) return;
 47             button1.IsEnabled = true;
 48             comboBox1.Text = comboBox1.Items[0].ToString();
 49             comboBox2.ItemsSource = SerialPortHelper.GetBaudRates();
 50             comboBox2.Text = comboBox2.Items[9].ToString();
 51             comboBox3.ItemsSource = SerialPortHelper.GetParities();
 52             comboBox3.Text = comboBox3.Items[0].ToString();
 53             comboBox4.ItemsSource = SerialPortHelper.GetStopBits();
 54             comboBox4.Text = comboBox4.Items[1].ToString();
 55             comboBox5.ItemsSource = SerialPortHelper.GetDataBits();
 56             comboBox5.Text = comboBox5.Items[1].ToString();
 57             comboBox6.ItemsSource = SerialPortHelper.GetFlowControls();
 58             comboBox6.Text = comboBox6.Items[0].ToString();
 59         }
 60 
 61         private void Window_Loaded(object sender, RoutedEventArgs e)
 62         {
 63             LoadParameters();
 64         }
 65 
 66         private void EnableConfig(bool enable)
 67         {
 68             if (enable) button1.Content = "开启";
 69             else button1.Content = "关闭";
 70             label1.IsEnabled = enable;
 71             label2.IsEnabled = enable;
 72             label3.IsEnabled = enable;
 73             label4.IsEnabled = enable;
 74             label5.IsEnabled = enable;
 75             label6.IsEnabled = enable;
 76             label7.IsEnabled = enable;
 77             comboBox1.IsEnabled = enable;
 78             comboBox2.IsEnabled = enable;
 79             comboBox3.IsEnabled = enable;
 80             comboBox4.IsEnabled = enable;
 81             comboBox5.IsEnabled = enable;
 82             comboBox6.IsEnabled = enable;
 83             textBox1.IsEnabled = enable;
 84         }
 85 
 86         SerialPort serialPort;
 87 
 88         private void button1_Click(object sender, RoutedEventArgs e)
 89         {
 90             if(button1.Content.ToString() == "开启")
 91             {
 92                 try
 93                 {
 94                     if(!int.TryParse(textBox1.Text,out int result))
 95                     {
 96                         MessageBox.Show("超时时间设置错误!");
 97                         return;
 98                     }
 99 
100                     serialPort = new SerialPort(comboBox1.Text, 
101                         SerialPortHelper.GetBaudRate(comboBox2.Text),
102                         SerialPortHelper.GetParity(comboBox3.Text), 
103                         SerialPortHelper.GetDataBit(comboBox5.Text),
104                         SerialPortHelper.GetStopBit(comboBox4.Text))
105                     { 
106                         Handshake = SerialPortHelper.GetFlowControl(comboBox6.Text),
107                         ReadTimeout = result
108                     };
109                     serialPort.Encoding = Encoding.ASCII;
110                     serialPort.DataReceived += SerialPort_DataReceived;
111                     serialPort.Open();
112                     EnableConfig(false);
113                     EnableReceiveAndSendGroup(false,true);
114                 }
115                 catch(Exception ex)
116                 {
117                     serialPort.Close();
118                     MessageBox.Show(ex.Message);
119                 }
120             }
121             else
122             {
123                 serialPort.Close();
124                 EnableConfig(true);
125                 EnableReceiveAndSendGroup(false,false);
126             }
127         }
128 
129         private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
130         {
131             textBox2.Dispatcher.Invoke(new Action(() => 
132             {
133                 textBox2.Text += serialPort.ReadExisting();
134             }));
135         }
136 
137         private void button2_Click(object sender, RoutedEventArgs e)
138         {
139             string text = textBox3.Text + "\r";
140             serialPort.Write(Encoding.ASCII.GetBytes(text), 0, text.Length);
141         }
142 
143         private void button3_Click(object sender, RoutedEventArgs e)
144         {
145             serialPort.Write(Encoding.ASCII.GetBytes(textBox3.Text), 0, textBox3.Text.Length);
146         }
147     }
148 }
代码语言:javascript
复制
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace SerialPortDebug
 7 {
 8     class EnumHelper
 9     {
10         public static T GetValue<T>(string valueString) => (T)Enum.Parse(typeof(T), valueString);
11     }
12 }
代码语言:javascript
复制
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.IO.Ports;
 6 
 7 namespace SerialPortDebug
 8 {
 9     class SerialPortHelper
10     {
11         public static string[] GetSerialPorts() => SerialPort.GetPortNames().OrderBy(x => x).ToArray();
12         public static string[] GetBaudRates() => new string[] { "256000", "128000", "115200", "57600", "56000", "43000", "38400", "28800", "19200", "9600", "4800", "2400", "1200", "600", "300", "110" };
13         public static string[] GetParities() => Enum.GetNames(typeof(Parity));
14         public static string[] GetStopBits() => Enum.GetNames(typeof(StopBits));
15         public static string[] GetDataBits() => new string[] { "7", "8", "9" };
16         public static string[] GetFlowControls() => Enum.GetNames(typeof(Handshake));
17 
18         public static int GetBaudRate(string baudRates) => Convert.ToInt32(baudRates);
19         public static Parity GetParity(string parity) => EnumHelper.GetValue<Parity>(parity);
20         public static StopBits GetStopBit(string stopbit) => EnumHelper.GetValue<StopBits>(stopbit);
21         public static int GetDataBit(string dataBit) => Convert.ToInt32(dataBit);
22         public static Handshake GetFlowControl(string flowControl) => EnumHelper.GetValue<Handshake>(flowControl);
23 
24     }
25 }

运行结果如下:

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-02-08 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档