Color different parts of a RichTextBox string

前端 未结 9 646
暖寄归人
暖寄归人 2020-11-22 08:10

I\'m trying to color parts of a string to be appended to a RichTextBox. I have a string built from different strings.

string temp = \"[\" + DateTime.Now.ToSh         


        
相关标签:
9条回答
  • 2020-11-22 08:48
    private void Log(string s , Color? c = null)
            {
                richTextBox.SelectionStart = richTextBox.TextLength;
                richTextBox.SelectionLength = 0;
                richTextBox.SelectionColor = c ?? Color.Black;
                richTextBox.AppendText((richTextBox.Lines.Count() == 0 ? "" : Environment.NewLine) + DateTime.Now + "\t" + s);
                richTextBox.SelectionColor = Color.Black;
    
            }
    
    0 讨论(0)
  • 2020-11-22 08:50

    Using Selection in WPF, aggregating from several other answers, no other code is required (except Severity enum and GetSeverityColor function)

     public void Log(string msg, Severity severity = Severity.Info)
        {
            string ts = "[" + DateTime.Now.ToString("HH:mm:ss") + "] ";
            string msg2 = ts + msg + "\n";
            richTextBox.AppendText(msg2);
    
            if (severity > Severity.Info)
            {
                int nlcount = msg2.ToCharArray().Count(a => a == '\n');
                int len = msg2.Length + 3 * (nlcount)+2; //newlines are longer, this formula works fine
                TextPointer myTextPointer1 = richTextBox.Document.ContentEnd.GetPositionAtOffset(-len);
                TextPointer myTextPointer2 = richTextBox.Document.ContentEnd.GetPositionAtOffset(-1);
    
                richTextBox.Selection.Select(myTextPointer1,myTextPointer2);
                SolidColorBrush scb = new SolidColorBrush(GetSeverityColor(severity));
                richTextBox.Selection.ApplyPropertyValue(TextElement.BackgroundProperty, scb);
    
            }
    
            richTextBox.ScrollToEnd();
        }
    
    0 讨论(0)
  • 2020-11-22 08:53

    This is the modified version that I put in my code (I'm using .Net 4.5) but I think it should work on 4.0 too.

    public void AppendText(string text, Color color, bool addNewLine = false)
    {
            box.SuspendLayout();
            box.SelectionColor = color;
            box.AppendText(addNewLine
                ? $"{text}{Environment.NewLine}"
                : text);
            box.ScrollToCaret();
            box.ResumeLayout();
    }
    

    Differences with original one:

    • possibility to add text to a new line or simply append it
    • no need to change selection, it works the same
    • inserted ScrollToCaret to force autoscroll
    • added suspend/resume layout calls
    0 讨论(0)
提交回复
热议问题