Rich Text Box how to highlight text block

29,985

Solution 1

I think you are looking for ScintillaNET.

On the other hand if you want to do this by yourself in RTB then you can do it by first finding the lineNumber using TextBoxBase.Lines property. Then ...

//Select the line from it's number
startIndex = richTextBox.GetFirstCharIndexFromLine(lineNumber);
richTextBox.Select(startIndex, length);

//Set the selected text fore and background color
richTextBox.SelectionColor = System.Drawing.Color.White;
richTextBox.SelectionBackColor= System.Drawing.Color.Blue;

Solution 2

Yes you can set the BackColor of a RichTextBox Selection using the RichTextBox.SelectionBackColor Property.

int blockStart = 1; //arbitrary numbers to test
int blockLength = 15;
richTextBox1.SelectionStart = blockStart;
richTextBox1.SelectionLength = blockLength;
richTextBox1.SelectionBackColor = Color.Yellow;

Solution 3

Here I have created CustomRichTextBox to achieve this.

The source code a long with scenario is explained here. If you interested then you can reuse this usercontrol directly without worry about much

Scenario

https://sites.google.com/site/greateindiaclub/mobil-apps/windows8/customwpfrichtextboxwithcolorchangeandhighlightfunctionality

source code:

https://github.com/boobalaninfo/CustomRichTextBoxWithHighligh

Share:
29,985
TtT23
Author by

TtT23

Updated on July 09, 2022

Comments

  • TtT23
    TtT23 almost 2 years

    I need a certain portion of my text in RTB to be highlighted not in the sense of changing the font style/color, but in the sense of making a block selection with a particular color. This is similar to how Visual Studio highlights a line during debug mode.

    How can I accomplish this feature using RTB or rather, is it even possible? If it isn't possible, I'd like to hear another way of performing the above task.

  • Jack
    Jack about 9 years
    Aren't you ignoring the GetFirstCharIndexFromLine() return value instead of save it into startIndex variable?