简体   繁体   中英

Highlight Entire Line in RichTextBox C#

I have a richtextbox in my C# winforms application and cannot figure out a way to highlight the entire line (the text part + any empty spaces). I am only able to highlight the text on the line using the following code:

firstCharIndex = richTextBox.Text.IndexOf(header);
headerLine = richTextBox.GetLineFromCharIndex(firstCharIndex);
headerLineText = richTextBox.Lines[headerLine];

int lastCharIndex = richTextBox.GetFirstCharIndexFromLine(headerLine + 1);

//richTextBox.Select(firstCharIndex, headerLineText.Length);
richTextBox.Select(firstCharIndex, lastCharIndex - firstCharIndex);

if (richTextBox.SelectionBackColor != System.Drawing.Color.DarkGray)
{
    richTextBox.SelectionBackColor = System.Drawing.Color.DarkGray;
}

Use the second overload of "select" for less calculations.

Look into comments.

        //Rich text box
        richTextBox1.Text = "test test1 test test                              ";

        //Get the first index in the line from where you want to select.
        int firstCharIndex = richTextBox1.Text.IndexOf("test1");

        //Get the line based on character index.
        int line = richTextBox1.GetLineFromCharIndex(firstCharIndex);

        //Get the line it self.
        string headerLineText = richTextBox1.Lines[line];

        //Use second ovrload of select method and pass length of the line as second parameter
        //with the below approach, you can start highlighting from any where in the line.
        richTextBox1.Select(firstCharIndex, headerLineText.Length- firstCharIndex);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM