Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
125 views
in Technique[技术] by (71.8m points)

c# - Highlighting a line in a RichTextBox1, line number = a variable

I have a variable, lets say it = 5, and then I would like the line number 5 to be highlighted "blue" in my RichTextBox1. is that possible at all?

Or should I use something like a ListBox, DataGridView etc.

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This will highlight the text in a given line in a RichTextBox if WordWrap is off:

void highLightALine(RichTextBox rtb, int line, Color hiLight)
{
    int i1 = rtb.GetFirstCharIndexFromLine(line);
    int i2 = rtb.GetFirstCharIndexFromLine(line + 1);
    if (i2 < 0) i2 = rtb.Text.Length;

    rtb.SelectionStart = i1;
    rtb.SelectionLength = i2 - i1;
    rtb.SelectionBackColor = hiLight;
}

Note that if WordWrap is true it will still highlight the line but only as far as it is visible. Its continuation on the next line will not be changed.

Also note that only Text can be highlighted. Trailing empty space can't be highlighted afaik. Here is an example of trying to owner-draw an RTB subclass..


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...