Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change color of text within a WinForms RichTextBox [duplicate]

I have a RichTextBox that I write a string to every time I click a Form button. Each string begins with the string "Long" or "Short" and ends with a newline. Each time I add a string, it appends to the bottom of the RichTextBox. I'd like to color each line red if it beings with "Long" and blue if it begins with "Short". How can I do this?

like image 862
Addie Avatar asked Mar 27 '10 00:03

Addie


People also ask

How to change font color in RichTextBox c#?

Richtextbox font colorForeColor = Color. FromArgb(255, 108, 105, 105);

How do I make text bold in RichTextBox C#?

SelectionFont = new Font(textBox. Font, FontStyle. Bold);

What is rich text box?

The RichTextBox control enables you to display or edit flow content including paragraphs, images, tables, and more. This topic introduces the TextBox class and provides examples of how to use it in both Extensible Application Markup Language (XAML) and C#.

What is rich text box in visual basic?

The RichTextBox is similar to the TextBox, but it has additional formatting capabilities. Whereas the TextBox control allows the Font property to be set for the entire control, the RichTextBox allows you to set the Font, as well as other formatting properties, for selections within the text displayed in the control.


2 Answers

Sure, so what you can do is use the SelectionStart, SelectionLength and SelectionColor properties to accomplish this. It works quite well.

Check out this page for info on these properties.

You can know the length of the RichTextBox text and color this as you go by setting the SelectionStart property to the current length, get the Length of the string you are going to append, set the SelectionLength and then set the SelectionColor as appropriate. Rinse and repeat for each string added.

int length = richTextBox.TextLength;  // at end of text richTextBox.AppendText(mystring); richTextBox.SelectionStart = length; richTextBox.SelectionLength = mystring.Length; richTextBox.SelectionColor = Color.Red; 

Something like that. That's how I remember it working.

like image 75
itsmatt Avatar answered Oct 02 '22 15:10

itsmatt


I was just doing this in a program I was writing. I was doing something like @itsmatt but I feel a bit simpler. You are able to just set the Selectioncolor and from that point on the RichTextBox will be that color until you change it to something else. If you are testing every line this seems to work out well and is easy.

if(myString == "Long")  {    richTextBox.SelectionColor = Color.Red;  } else {   richTextBox.SelectionColor = Color.Green } richTextBox.AppendText(myString); 
like image 26
DTown Avatar answered Oct 02 '22 16:10

DTown