I want to coloured different parts of a richtextbox with different colors, same as posted here.
But with one difference, in my case I need to use the method Insert of the richtextbox to insert message at the top.
I was using classical method:
myRichTextBox.Text.Insert(0, myMessage);
but using it I cannot coloured different parts of the message so I have done below extension methods:
public static class RichTextBoxExtensions
{
public static string Insert(this string str, int index, RichTextBox box, string text, Color color)
{
box.SelectionStart = box.TextLength;
box.SelectionLength = 0;
box.SelectionColor = color;
//box.Text = str.Insert(0, box, text, color);
box.Text = str.Insert(index, text);
box.SelectionColor = box.ForeColor;
return box.Text;
}
}
and then I use it by calling in the following way from any point of my program:
private void PrintMessage(RichTextBox box, string message, Color color)
{
box.Text = box.Text.Insert(0, box, message, color);
}
But it is not working, it throws an exception in extension method Insert in line:
box.Text = str.Insert(0, box, text, color);
It says "Stack overflow". Any ideas?
UPDATED:
private void PrintMessage(RichTextBox box, string message, Color color)
{
box.SelectedText = box.SelectedText.Insert(0, box, message, color);
}
public static class RichTextBoxExtensions
{
public static string Insert(this string str, int index, RichTextBox box, string text, Color color)
{
box.SelectionStart = box.TextLength;
box.SelectionLength = 0;
box.SelectionColor = color;
box.SelectedText = str.Insert(index, text);
box.SelectionColor = box.ForeColor;
return box.Text;
}
}
But it does not work, text does not appear coloured.
NOTE:
I need text to be added at the top of the richtextbox control, not at the bottom, so I was using Insert instead of AppendText.
UPDATE 2: Using AppendText and setting SelectionStart to 0 to append text at the top of the richtextbox as TaW says here, fails the first time you print a message into the richtextbox. Rest of time (not the first) is going ok.
So how to make it work also for the first string appended into the richtextbox?
public static void AppendText(this RichTextBox rtb, string text, Color color)
{
rtb.SelectionStart = 0; // set the cursor to the target position
rtb.SelectionLength = 0; // nothing selected, yet
rtb.SelectedText = text; // this inserts the new text
rtb.SelectionLength = text.Length; // now we prepare the new formatting
rtb.SelectionColor = color;
}
Insert
method calls itself from inside itself. – Equalskstring
doesn't know squat about rich text, so your extension should probably go against a RichTextBox control, not a string variable, like in the linked article. Use SelectedText versus Text. The Text property ignores the rich text attributes. – LarsTechrichTextBox1.SelectionStart = 0; richTextBox1.SelectionLength = 0; richTextBox1.SelectedText = myMessage
- Never touch the Text property or you will mess up previous formatting. – TaW