How to have alternating line colors for a Winforms RichTextBox?

心已入冬 提交于 2019-12-10 15:12:05

问题


Something that looks like this:

Is there a line-like property where I could do?:

foreach line ...
    line.BackColor = Colors.Gray;

Lines[i] property returns just a string.


回答1:


A not so great solution would be to append extra text onto each line and then highlight the full text. So something like this:

// Update lines to have extra length past length of window
string[] linez = new string[richTextBox1.Lines.Length];
for (int i = 0; i < richTextBox1.Lines.Length; i++)
{
   linez[i] = richTextBox1.Lines[i] + new string(' ', 1000);
}
richTextBox1.Clear();
richTextBox1.Lines = linez;

for(int i = 0; i < richTextBox1.Lines.Length; i++)
{
   int first = richTextBox1.GetFirstCharIndexFromLine(i);
   richTextBox1.Select(first, richTextBox1.Lines[i].Length);
   richTextBox1.SelectionBackColor = (i % 2 == 0) ? Color.Red : Color.White;
   richTextBox1.SelectionColor = (i % 2 == 0) ? Color.Black : Color.Green;
}
richTextBox1.Select(0,0);

It would look like this:



来源:https://stackoverflow.com/questions/5982006/how-to-have-alternating-line-colors-for-a-winforms-richtextbox

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