serialPort1_DataReceived 执行二次 messagebox

本文介绍了一个简单的C#程序片段,该程序用于在通过串口接收数据之前检查是否已输入单据编号。若未输入,则会弹出提示框,并通过睡眠和清除输入缓冲区来避免重复提示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
    if (textBox1.Text.Trim().Length == 0 )
    {
        System.Threading.Thread.Sleep(200); //读取速度太慢,加Sleep延长读取时间, 不可缺少
        serialPort1.DiscardInBuffer();  //如果不执行上面的二行代码,messagebox会弹出二次窗口
        MessageBox.Show(string.Format("请先输入单据编号"));
    }
}
using leida2.BLL; using System; using System.Windows.Forms; namespace leida2 { public partial class Form1 : Form { private readonly RadarService _radarService; public Form1() { InitializeComponent(); _radarService = new RadarService(); _radarService.HexDataReceived += SerialPort_DataReceived; RefreshPortList(); } private void RefreshPortList() { comboBox1.Items.Clear(); comboBox1.Items.AddRange(_radarService.GetAvailablePorts()); if (comboBox1.Items.Count > 0) comboBox1.SelectedIndex = 0; } private void button1_Click(object sender, EventArgs e) { if (comboBox1.SelectedItem == null) { MessageBox.Show("请先选择串口"); return; } _radarService.OpenPort(comboBox1.SelectedItem.ToString()); } private void button2_Click(object sender, EventArgs e) { RefreshPortList(); } private void SerialPort_DataReceived(string data) { if (textBox1.InvokeRequired) { textBox1.BeginInvoke(new Action(() => { textBox1.AppendText(data); textBox1.SelectionStart = textBox1.TextLength; textBox1.ScrollToCaret(); })); } else { textBox1.AppendText(data); textBox1.SelectionStart = textBox1.TextLength; textBox1.ScrollToCaret(); } } protected override void OnFormClosing(FormClosingEventArgs e) { base.OnFormClosing(e); _radarService.Dispose(); } } } using leida2.DAL; using System; using System.Text; namespace leida2.BLL { public class RadarService : IDisposable { private readonly SerialPortDAL _serialPortDAL; public event Action<string> HexDataReceived; public event Action<int> DistanceReceived; public event Action<string> RawDataReceived; public RadarService() { _serialPortDAL = new SerialPortDAL(); _serialPortDAL.DataReceived += ProcessIncomingData; } public string[] GetAvailablePorts() => _serialPortDAL.GetAvailablePorts(); public void OpenPort(string portName) => _serialPortDAL.OpenPort(portName); public void ClosePort() => _serialPortDAL.ClosePort(); private void ProcessIncomingData(byte[] data) { try { string hexData = SerialPortDAL.BytesToHexString(data); HexDataReceived?.Invoke(hexData); if (data.Length >= 2) { int distance = data[0] | (data[1] << 8); DistanceReceived?.Invoke(distance); } string rawData = Encoding.ASCII.GetString(data); RawDataReceived?.Invoke(rawData); } catch (Exception ex) { Console.WriteLine($"数据处理错误:{ex.Message}"); } } //16 public static int ParseDistanceFromHex(string hexString) { if(string.IsNullOrEmpty(hexString)) return 0; if(hexString.Length < 4) return 0; string distanceHex = hexString.Length > 4 ? hexString.Substring(0, 4) : hexString; byte lowByte = Convert.ToByte(distanceHex.Substring(0, 2), 16); byte highByte = Convert.ToByte(distanceHex.Substring(2, 2), 16); return lowByte | (highByte << 8); } public void Dispose() { _serialPortDAL.Dispose(); } } } using System; using System.IO.Ports; using System.Text; namespace leida2.DAL { public class SerialPortDAL : IDisposable { private readonly SerialPort _serialPort = new SerialPort(); // 声明一个事件,用于在接收到数据时通知订阅者 public event Action<byte[]> DataReceived; public SerialPortDAL() { _serialPort.BaudRate = 23400; _serialPort.DataBits = 8; _serialPort.Parity = Parity.None; _serialPort.StopBits = StopBits.One; _serialPort.DataReceived += SerialPort_DataReceived; } //获取端口 public string[] GetAvailablePorts() { return SerialPort.GetPortNames(); } //打开串口 public void OpenPort(string portName) { if (_serialPort.IsOpen) { _serialPort.Close(); } _serialPort.PortName = portName; try { _serialPort.Open(); } catch (Exception ex) { Console.WriteLine($"打开串口失败:{ex.Message}"); throw; } } //关闭串口 public void ClosePort() { if (_serialPort.IsOpen) { _serialPort.Close(); } } // private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { try { int bytesToRead = _serialPort.BytesToRead; byte[] buffer = new byte[bytesToRead]; _serialPort.Read(buffer, 0, bytesToRead); DataReceived?.Invoke(buffer); } catch (Exception ex) { Console.WriteLine($"数据错误{ex.Message}"); } } // 添加字节数组转16进制字符串的方法 public static string BytesToHexString(byte[] bytes) { if (bytes == null || bytes.Length == 0) return string.Empty; return BitConverter.ToString(bytes).Replace("-", ""); } public void Dispose() { ClosePort(); _serialPort.Dispose(); } } } 我的代码是不是写错了
07-13
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值