C#wpf实现一个串口通信助手

实现步骤

1、获取本机所有串口名;

2、实例化一个 SerialPort对象;

3、给数据接收事件添加响应;

示例代码:

        private SerialPort serialPort1;
        string receivedata;
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            string[] ports=SerialPort.GetPortNames();
            foreach (string port in ports)
                CboxPorts.Items.Add(port);
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                serialPort1 = new SerialPort();
                serialPort1.PortName = CboxPorts.Text;//连接端口
                serialPort1.BaudRate= Convert.ToInt32(Cboxbaudrate.Text);//设置波特率
                serialPort1.DataBits = Convert.ToInt32(Cboxdata.Text);//设置数据位
                serialPort1.StopBits = (StopBits)Enum.Parse(typeof(StopBits), Cboxstop.Text);//设置停止位
                serialPort1.Parity = (Parity)Enum.Parse(typeof(Parity), Cboxparity.Text);//设置校验位
                serialPort1.Open();
                if(serialPort1.IsOpen)
                    MessageBox.Show("打开成功!");
                serialPort1.DataReceived += SerialPort1_DataReceived;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void SerialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                //throw new NotImplementedException();
                int count = serialPort1.ReadByte();
                Byte[] buffer = new Byte[count];
                serialPort1.Read(buffer, 0, count);
                
                receivedata =receivedata+DateTime.Now+"\t"+ Encoding.UTF8.GetString(buffer)+"\r\n";
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    textboxReceive.Text=receivedata;
                }));//创建异步线程接收
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            if (serialPort1.IsOpen)
            {
                serialPort1.Close();
                MessageBox.Show("关闭成功!");
            }
            else
                MessageBox.Show("端口未打开!");
        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            if (serialPort1.IsOpen)
                serialPort1.WriteLine(DateTime.Now+"\t"+textboxSend.Text + "\r");
            else
                MessageBox.Show("串口未打开!");
        }

效果展示

C#wpf实现一个串口通信助手_第1张图片

你可能感兴趣的:(c#,开发语言,windows,wpf)