【问题标题】:pause rich text box and then resume again暂停富文本框,然后再次恢复
【发布时间】:2016-01-18 21:22:02
【问题描述】:

我在做什么:

我每秒不断地从串行端口接收一串数据。我正在处理它并在富文本框中显示此字符串。

问题:

我希望用户浏览旧字符串并复制任何内容,但用户不能这样做,因为数据每秒都会出现并且会发生自动滚动。

我想要的解决方案:

我正在考虑设置一个“暂停”复选框。当用户检查它时富文本框的更新停止。用户可以进入历史并复制一个字符串。但与此同时,我不想停止从串行端口传入的字符串,因为我也在处理传入的字符串。

因此,当用户取消选中“暂停”复选框时,在用户选中“暂停”复选框时较早到达的所有字符串也会与新字符串一起出现在富文本框中。

有办法吗?

【问题讨论】:

  • checkbox勾选时,基本上把串口传入的数据写入另一个缓冲区,不要写入RTFBox,只要checkbox的值再次更改为true,将所有保存的字符串从后台缓冲区写入rtfbox并继续写入主缓冲区/ RTFBox。那将是最简单的解决方案。

标签: c# winforms serial-port


【解决方案1】:

假设当您选中暂停按钮时,每个传入的文本都将附加到 StringBuilder 而不是 RichTextBox。当用户取消选中暂停按钮时,您将所有内容从 StringBuilder 复制到 RichTextBox

// Assume that these are somewhere globals of your forms
RichTextBox rtb = new RichTextBox();
CheckBox chkPause = new CheckBox();
StringBuilder sb = new StringBuilder();

protected void chkPause_CheckedChanged(object sender, EventArgs e)
{
    if(!chkPause.Checked)
    {
        rtb.AppendText = sb.ToString();
        // Do not forget to clear the buffer to avoid errors 
        // if the user repeats the stop/go cycle.
        sb.Clear();
    }
    else
    {
        // Start a timer to resume normal flow after a timer elapses.
        System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
        t.Interval = GetSuspensionMilliseconds();
        t.Tick += onTick;
        t.Start();
    }
}

protected void onTick(object sender, EventArgs e)
{
    if (chkPause.Checked)
    {
        // Set to false when the timing elapses thus triggering the CheckedChanged event 
        chkPause.Checked = false;
        System.Windows.Forms.Timer t = sender as System.Windows.Forms.Timer;
        t.Stop();
    }
}

现在在传入数据被传递到您可以添加的 RichTextBox 的位置

....
string incomingData = ReceiveDataFromSerialPort();
if(chkPause.Checked)
   sb.AppendLine(incomingData);
else
   rtb.AppendText = incomingData;

【讨论】:

  • 感谢您的回复。这也是一个上帝的想法,让用户可以暂停更新到富文本框几秒钟之类的时间吗?这种情况下的时间上限是多少
  • 我不能说。这应该是您的用户的可配置选项。有时 30 秒,最多 2 分钟。除非您每秒收到大量数据,否则这不应该是内存问题。超时是一个好主意,并且可以使用计时器轻松实现,该计时器在您获得检查时启动并在给定时间后自动取消检查
  • 添加了一个定时器示例来恢复正常的数据流入。
  • 嗯,StringBuilder 没有存储颜色的规定。但是,如果这些颜色是对传入数据进行某种详细说明的结果,那么您需要将此详细说明也应用于存储在 StringBuilder 中的字符串。您可以取回 StringBuilder 内容,将其拆分为多行,然后处理每一行添加所需的颜色。
  • AppendLine 在 stringbuilder 中存储的字符串末尾添加换行符。您取回 StringBuilder 内容 (ToString()) 并在换行符处将其拆分 (string.Split(newline constant)) 获取字符串数组,然后从同一行的颜色中获取并再次拆分行的数据部分
猜你喜欢
  • 2021-11-25
  • 2022-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多