C#关于简单串口通信的winfrom客户端
UI界面图:
、
发送端口配置相关初始化:
private void Form1_Load(object sender, EventArgs e) { // 获取当前串口名的数组 string[] ports = SerialPort.GetPortNames(); comboBoxCom.Items.AddRange(ports); // 初始化数据位下拉框 comboBoxDatabit.DropDownStyle = ComboBoxStyle.DropDownList; comboBoxDatabit.DataSource = Enum.GetValues(typeof(SerialPortDatabits)); comboBoxDatabit.DisplayMember = "ToString"; comboBoxDatabit.SelectedIndex = 0; // 默认选择none // 初始化数据位下拉框 comboBoxBaud.DropDownStyle = ComboBoxStyle.DropDownList; // 获取枚举成员的名称数组 string[] baudRateNames = Enum.GetNames(typeof(SerialPortBaudRates)); // 创建一个新的字符串数组,包含完整的枚举成员字符串 string[] baudRateDisplayNames = new string[baudRateNames.Length]; for (int i = 0; i < baudRateNames.Length; i++) { SerialPortBaudRates enumValue = (SerialPortBaudRates)Enum.Parse(typeof(SerialPortBaudRates), baudRateNames[i]); baudRateDisplayNames[i] = $"{(int)enumValue}"; } // 绑定数据源到下拉框,并设置显示的完整成员名称 comboBoxBaud.DataSource = baudRateDisplayNames; comboBoxBaud.DisplayMember = "ToString"; comboBoxBaud.SelectedIndex = 8; // 默认选择9600 comboBoxBIP.DropDownStyle = ComboBoxStyle.DropDownList; comboBoxBIP.DataSource = Enum.GetValues(typeof(Parity)); comboBoxBIP.DisplayMember = "ToString"; comboBoxBIP.SelectedIndex = 0; // 默认选择none comboBoxStop.DropDownStyle = ComboBoxStyle.DropDownList; comboBoxStop.DataSource = Enum.GetValues(typeof(StopBits)); comboBoxStop.DisplayMember = "ToString"; comboBoxStop.SelectedIndex = 0; // 默认选择none }
打开串口按钮点击事件:
private void buttonOn_Click(object sender, EventArgs e) { if (buttonOn.Text == "打开串口") { try { serialPort.PortName= comboBoxCom.Text; // 获取选择的串口端口 if(Enum.TryParse(comboBoxBaud.Text, out SerialPortBaudRates baudRate)) { serialPort.BaudRate = baudRate; } if (Enum.TryParse(comboBoxBIP.Text, out Parity parity)) { serialPort.Parity = parity; } if (Enum.TryParse(comboBoxDatabit.Text, out SerialPortDatabits databit)) { serialPort.DataBits = databit; } if (Enum.TryParse(comboBoxStop.Text, out StopBits stopBit)) { serialPort.StopBits = stopBit; } // 设置DataCheck属性为非空值 serialPort.DataCheck = (data) => { // 编写逻辑来检查数据 return data.Count > 0; // 示例:检查数据列表是否为空 }; serialPort.OpenPort(); if (serialPort.IsOpen) { MessageBox.Show("串口已打开"); buttonOn.Text = "关闭串口"; } else { MessageBox.Show("串口打开失败"); } } catch (Exception ex) { MessageBox.Show("串口打开失败" + ex.ToString(), "警告", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { try { serialPort.ClosePort(); MessageBox.Show("串口已关闭"); } catch (Exception ex) { } buttonOn.Text = "打开串口"; } }
发送数据按钮点击事件:
/// <summary> /// 发送数据 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void butSending_Click(object sender, EventArgs e) { string Str = richTextBox1.Text; // 获取发送文本框里的数据 Str= Str.PadRight(9, ' '); var buffer= Encoding.ASCII.GetBytes(Str); try { if (Str.Length > 0) { byte[] bytes = Encoding.ASCII.GetBytes(Str); //serialPort.WriteData(bytes); // 串口发送数据 serialPort.WriteData(bytes ); // 串口发送数据 } } catch (Exception) { } }