Take the 2-minute tour ×

Say I have a WPF RichTextBox with the following content:

Hello Hello // <== here is a line break \r\n
Turn Your Radio On!

I then read the text from the box with the following code:

public static string GetText(this RichTextBox box)
    var range = new TextRange(box.Document.ContentStart,

    return range.Text;

After that I retrieve var index = text.IndexOf("Hello\r\nTurn") and var length = "Hello\r\nTurn".Length.
Based on index and length: How can I select that text in the RichTextBox? The index/length in the plain string does not match up with what the RichTextBox expects.

I tried the approach from the answer here, but this does not seem to work if the text contains a line wrap / paragraph.

Note: My string manipulation (finding index / length) is considerably more complex than the example, but the example given here describes my problem well

share|improve this question
I tried GetPositionAtOffset and it was no help. –  Blam Feb 27 '12 at 23:30
@H.B. I added WPF to the title to make it apparent, that it is not about the WinForms RichTextBox. Is this somehow discouraged? –  yas4891 Feb 28 '12 at 5:24
@yas4891: Yes, because we have the tag section for that. People usually check the tags before making assumptions, especially if it's not obvious. (Also you even mention WPF in the first sentence so it should be very clear) –  H.B. Feb 28 '12 at 5:28

1 Answer 1

up vote 0 down vote accepted

The RichTextBox has a Selection property that you can call its "Select" method. It accepts 2 TextPointer objects, one for the selection start and the other for its end.


I don't think you the index and length properties will be good enough for you to select the text. You would have to get the real TextPointer.

Try using a method for finding specific words TextPointers such as the one specified in here -


share|improve this answer

Your Answer


