1
  public static void HighlightText(RichTextBox richTextBox,int startPoint,int endPoint, Color color)
    {
      //Trying to highlight charactars here
    }

Startpoint is the first character that should be highlighted and the endPoint the last one.

Have been searching the web for quiet a while now but i still haven't figured out how to solve my problem. I hope any of you knows how to solve this problem.

1 Answers1

1

Here is the general idea:

public static void HighlightText(RichTextBox richTextBox, int startPoint, int endPoint, Color color)
{
    //Trying to highlight charactars here
    TextPointer pointer = richTextBox.Document.ContentStart;
    TextRange range = new TextRange(pointer.GetPositionAtOffset(startPoint), pointer.GetPositionAtOffset(endPoint));
    range.ApplyPropertyValue(TextElement.BackgroundProperty, new SolidColorBrush(color));
}

However you will need to iterate through the document to get the correct text positions, since offset index number doesn't match number of characters. Some characters may represent multiple offset positions.

Here is the method that does that. I'm not aware of a way to do this without looping through the entire document.

public static void HighlightText(RichTextBox richTextBox, int startPoint, int endPoint, Color color)
{
    //Trying to highlight charactars here
    TextPointer pointer = richTextBox.Document.ContentStart;
    TextPointer start = null, end = null;
    int count = 0;
    while (pointer != null)
    {
        if (pointer.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
        {
            if (count == startPoint) start = pointer.GetInsertionPosition(LogicalDirection.Forward);
            if (count == endPoint) end = pointer.GetInsertionPosition(LogicalDirection.Forward);
            count++;
        }
        pointer = pointer.GetNextInsertionPosition(LogicalDirection.Forward);
    }
    if (start == null) start = richTextBox.Document.ContentEnd;
    if (end == null) end = richTextBox.Document.ContentEnd;

    TextRange range = new TextRange(start, end);
    range.ApplyPropertyValue(TextElement.BackgroundProperty, new SolidColorBrush(color));
}
Neil B
  • 2,096
  • 1
  • 12
  • 23
  • It seems to work for the first time the method is called. However when the method is called for the second time it doesnt seem to work properly. Hopefully you might have an idea to fix this problem? – Sander Boonstra Nov 19 '18 at 13:16