0

Trying to make this function change color of the line it receives. I doing a little notepad with a richtextbox1.

I've tried this code:

private string changeLineColor(string lineIn)
{
    string sb = lineIn;
    string mycolor = Color.Red.ToString();        
    foreach (char c in mycolor)
    {
        sb.Append(c);
    }
    return sb.ToString();
}
Jackdaw
  • 7,626
  • 5
  • 15
  • 33
  • It is a bit different then you think, but I guess this question will answer your need. https://stackoverflow.com/questions/28604252/how-to-change-part-of-text-color-at-richtextbox If it is not what you need, specify what exactly you would like to do – merof Mar 24 '23 at 13:05

1 Answers1

1

You can try the following extension method:

public static class RichTextBoxExt
{
    public static string AddColoredLine(this RichTextBox rtb, string line, Color tcolor)
    {
        int pos = rtb.SelectionStart;
        int len = rtb.SelectionLength;
        int end = rtb.TextLength;
        // Appends text to the current text of a text box.
        rtb.AppendText(line);
        rtb.SelectionStart = end;
        rtb.SelectionLength = line.Length;
        rtb.SelectionColor = tcolor;
        // Restore cursor position                   
        rtb.Select(pos, len); 
        return line;
    }
}

It append colored text and restore the previews selection and cursor position.

Use it like: richTextBox1.AddColoredLine("some_text", Color.Red);


A similar example you can find here:

Change color of text within a WinForms RichTextBox

Jackdaw
  • 7,626
  • 5
  • 15
  • 33
  • I dont want to select a line. It comes from another funtion. This doesn not work. thanks – Antony Code Mar 24 '23 at 14:26
  • 1
    @AntonyCode: You asked: **"Change string color one richtext line"**. To set color of the text in the "RichTexBox" you **MUST** select the text to set it color. – Jackdaw Mar 24 '23 at 16:05
  • 1
    @AntonyCode _I dont want to select a line. It comes from another funtion._ Then return RTF format and you must insert it correctly in the main RTF to not break it. – dr.null Mar 24 '23 at 17:52