【问题标题】:Richtextbox prepend new text with colorRichtextbox 为新文本添加颜色
【发布时间】:2016-06-29 11:09:21
【问题描述】:

我使用了一个富文本框来在我的 WinForms 中显示日志。

使用的语言是 C#。

该软件用于插入银行分行的数据,在新分行启动后我想显示一个新颜色的文本。

我看到了链接Color different parts of a RichTextBox string并成功实现。

我的问题是我想添加新行而不是追加。也就是说,新行将显示在顶部。

我可以通过将代码更改为box.Text=DateTime.Now.ToString("dd-MM-yyyy-hh-mm-ss") + ": " + text + box.Text来做到这一点

但整个文本的颜色正在改变。

这是用于追加的过程

            box.SelectionStart = box.TextLength;
        box.SelectionLength = 0;

        box.SelectionColor = color;

        box.AppendText(DateTime.Now.ToString("dd-MM-yyyy-hh-mm-ss") + ": " + text);
        box.SelectionColor = box.ForeColor;

这就是我所做的:

            box.Text=DateTime.Now.ToString("dd-MM-yyyy-hh-mm-ss") + ": " + text + box.text;
        box.SelectionStart = 0;
        box.SelectionLength = text.length;
        box.SelectionColor = color;

但这不起作用。

【问题讨论】:

    标签: c# winforms richtextbox


    【解决方案1】:

    1) 切勿直接更改已格式化的RichtTextBoxText 属性

    2) 追加使用RTB.AppendText函数

    3) 插入在任何其他位置p,包括开头使用这个:

    rtb.SelectionStart = s;            // set the cursor to the target position
    rtb.Selection.Length = 0;          // nothing selected, yet
    rtb.SelectedText = yourNewText;    // this inserts the new text 
    

    现在你可以添加你想要的格式了:

    rtb.SelectionStart = s;            // now we prepare the new formatting..
    rtb.SelectionLength = yourNewText.Length;   //.. by selecting the text
    rtb.SelectionColor = Color.Blue;   // and/or whatever you want to do..
    ...
    

    【讨论】:

    • 是的。这就是我正在寻找的解决方案。
    【解决方案2】:
        // Prepend, normal on first line, rest of lines gray italic
    
        private void PrependToRichTextbox(RichTextBox rt, string msg)
        {
            rt.SelectionStart = 0;
            rt.SelectionLength = 0;
            rt.SelectedText = msg + Environment.NewLine;
    
            int linecount = 0;
            foreach (var line in rt.Lines)
            {
                rt.Select(rt.GetFirstCharIndexFromLine(linecount), line.Length);
                rt.SelectionColor = linecount == 0 ? Color.Black : Color.Gray;
                Font currentFont = rt.SelectionFont;
                FontStyle newFontStyle;
                newFontStyle = linecount == 0 ? FontStyle.Regular : FontStyle.Italic;
                rt.SelectionFont = new Font(
                   currentFont.FontFamily,
                   currentFont.Size,
                   newFontStyle
                );
                linecount++;
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-07
      • 2014-03-11
      • 1970-01-01
      • 2021-11-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多