You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#使用ReadExisting()读取串口缓冲区时如何格式化对齐内容

串口电能表数据对齐展示解决方案

问题根因

当前直接拼接原始串口数据到TextBox出现排版混乱,核心原因有两点:

  • 默认TextBox使用比例字体,不同字符宽度不一致,空格无法实现对齐效果
  • 未对不同长度的列做固定宽度补位处理,且ReadExisting()可能返回半行数据,导致拆分列异常

方案1:TextBox + 等宽字体 + 列格式化

步骤1:调整控件基础属性

将TextBox的Font属性修改为等宽字体(推荐Consolas/Courier New),同时开启Multiline属性。

步骤2:修改数据处理逻辑

新增全局缓冲区存储未处理的碎片数据,收到完整行后做列对齐格式化再输出,代码如下:

// 全局变量:存储串口未处理的碎片数据
private string _serialBuffer = string.Empty;
// 可根据实际业务调整列固定宽度,单位为字符数
private const int Column1Width = 16;
private const int Column2Width = 22;

private void serialPort1_DataReceived_1(object sender, SerialDataReceivedEventArgs e)
{
    _serialBuffer += serialPort1.ReadExisting();
    // 循环处理缓冲区中所有完整行
    while (_serialBuffer.Contains(Environment.NewLine))
    {
        int newLinePos = _serialBuffer.IndexOf(Environment.NewLine);
        string fullRawLine = _serialBuffer.Substring(0, newLinePos);
        _serialBuffer = _serialBuffer.Substring(newLinePos + Environment.NewLine.Length);

        // 格式化行
        string formattedLine = FormatAlignedLine(fullRawLine);
        // UI线程更新
        this.Invoke(new Action(() =>
        {
            textBox1.AppendText(formattedLine + Environment.NewLine);
            textBox1.ScrollToCaret();
        }));
    }
}

// 行对齐格式化方法
private string FormatAlignedLine(string rawLine)
{
    // 按实际列分隔符修改,此处默认是制表符/空格分隔
    char[] separators = new[] { '\t', ' ' };
    string[] columns = rawLine.Split(separators, StringSplitOptions.RemoveEmptyEntries);
    
    if (columns.Length < 2) return rawLine;
    // 按固定宽度右补空格实现对齐,超过2列可自行扩展逻辑
    return columns[0].PadRight(Column1Width) + columns[1].PadRight(Column2Width) 
           + (columns.Length > 2 ? string.Join(" ", columns.Skip(2)) : string.Empty);
}

// 原Showdata方法可删除

方案2:DataGridView展示(更推荐)

如果不需要纯文本格式的输出,直接使用DataGridView控件可省去字符串格式化的步骤:

  • 窗体中添加DataGridView控件,提前设置2个固定宽度的列,可自定义对齐方式
  • 拆分每行的列数据后直接插入到DataGridView的行集合中即可自动对齐

内容的提问来源于stack exchange,提问作者Shay Avitapl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 18:09:03