C#--WPF--简单串口软件

C#--WPF--简单串口软件_第1张图片
后台代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO.Ports;
using System.Windows.Threading;

namespace FirstTest
{
    /// 
    /// MainWindow.xaml 的交互逻辑
    /// 
    public partial class MainWindow : Window
    {
        public SerialPort _serialPort = new SerialPort();
        public DispatcherTimer _timer = new DispatcherTimer();

        public MainWindow()
        {
            InitializeComponent();

            // 配置定时器
            _timer.Interval = TimeSpan.FromMilliseconds(500);
            _timer.Tick += timerTick;
            _timer.Start();

            // 初始化串口
            initSerial();
        }

        private void initSerial()
        {
            portCbm.Items.Clear();

            string[] ports = SerialPort.GetPortNames();//获取当前计算机的串行端口名的数组。

            for (int index = 0; index < ports.Length; index++)
            {
                portCbm.Items.Add(ports[index]);//添加item
                portCbm.SelectedIndex = index; //设置显示的item索引
            }

            baudCbm.SelectedIndex = 1 ;
        }

        public void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)//读取下位机的数据,显示在textBlock中
        {
            int len = this._serialPort.BytesToRead;
            byte[] buffer = new byte[len];

            this._serialPort.Read(buffer, 0, len);

            //string strData = BitConverter.ToString(buffer, 0, len);  // 16进制
            string strData = Encoding.Default.GetString(buffer); // 字符串

            Dispatcher.Invoke(() =>
            {
                //this.recvTextBox.Text += strData;
                //this.recvTextBox.Text += "-";//字符分隔-

                this.recvTextBox.AppendText(strData);
            });
        }

        private void openBtnClick(object sender, RoutedEventArgs s)
        {
            string strContent = this.openBtn.Content.ToString();
            if (strContent == "打开串口")
            {
                try
                {
                    _serialPort.PortName = portCbm.SelectedItem.ToString();//串口号
                    ComboBoxItem seletedItem = (ComboBoxItem)this.baudCbm.SelectedItem;
                    _serialPort.BaudRate = Convert.ToInt32(seletedItem.Content.ToString());//波特率
                    _serialPort.DataBits = 8;//数据位
                    _serialPort.StopBits = StopBits.One;//停止位
                    _serialPort.Parity = Parity.None;//校验位

                    _serialPort.Open();
                    _serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);//添加数据接收事件
                    _serialPort.DataReceived += DataReceivedHandler;

                    openBtn.Content = "关闭串口";
                }
                catch
                {
                    MessageBox.Show("打开串口失败", "错误");
                }
            }
            else
            {
                try
                {
                    _serialPort.DataReceived -= DataReceivedHandler;
                    _serialPort.Close();
                    openBtn.Content = "打开串口";
                }
                catch
                {
                    MessageBox.Show("关闭串口失败", "错误");
                }
            }
        }

        private void clearBtnClick(object sender, RoutedEventArgs s)
        {
            // 清空数据
            recvTextBox.Clear();
        }

        private void sendBtnClick(object sender, RoutedEventArgs s)
        {

        }

        private void timerTick(object sender, EventArgs e)
        {
            // 定时更新串口信息
            initSerial();
        }
    }
}

界面文件:

<Window x:Class="FirstTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:FirstTest"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="819">
    <Grid Margin="0,0,28,0">
        <ComboBox x:Name="portCbm" HorizontalAlignment="Left" Margin="69,50,0,0" VerticalAlignment="Top" Width="89"/>
        <ComboBox x:Name="baudCbm" HorizontalAlignment="Left" Margin="69,93,0,0" VerticalAlignment="Top" Width="89">
            <ComboBoxItem Content="9600"/>
            <ComboBoxItem Content="115200"/>
        </ComboBox>
        <Button x:Name="openBtn" Content="打开串口" HorizontalAlignment="Left" Margin="69,289,0,0" VerticalAlignment="Top" Width="75" Click="openBtnClick" Height="30"/>
        <Button x:Name="clearBtn" Content="清除数据" HorizontalAlignment="Left" Margin="69,348,0,0" VerticalAlignment="Top" Width="75" Click="clearBtnClick" Height="30" RenderTransformOrigin="0.4,0.467"/>
        <TextBox x:Name="recvTextBox" HorizontalAlignment="Left" Height="299" Margin="203,20,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="545"/>
        <Label Content="端口" HorizontalAlignment="Left" Margin="10,50,0,0" VerticalAlignment="Top"/>
        <Label Content="波特率" HorizontalAlignment="Left" Margin="10,93,0,0" VerticalAlignment="Top"/>
        <GroupBox Header="设置" HorizontalAlignment="Left" Height="399" Margin="10,10,0,0" VerticalAlignment="Top" Width="188"/>
        <Button x:Name="sendBtn" Content="发送" HorizontalAlignment="Left" Margin="668,348,0,0" VerticalAlignment="Top" Width="75" Height="41" Click="sendBtnClick"/>
        <TextBox x:Name="sendTextBox" HorizontalAlignment="Left" Height="41" Margin="203,348,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="451"/>

    </Grid>
</Window>

你可能感兴趣的:(C#,WPF)