Change color of text within a WinForms RichTextBox [duplicate]

和自甴很熟 提交于 2019-11-27 01:40:52

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.

DTown

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!