title: Can we programmatically search highlighted text in RichTextBox of WPF
body: <p>As shown at the end below, using Microsoft WORD VBA, we can search all highlighted texts in <code>MS WORD</code> document. Same can be achieved using C# in a legacy <a href="https://docs.microsoft.com/en-us/office/dev/add-ins/overview/learning-path-transition" rel="nofollow noreferrer">MS Office VSTO add-in</a>. <strong>Question</strong>: How can we programmatically get TexRanges of all <code>highlighted</code> texts in a <code>WPF RichTextBox</code>?</p>
  <p><strong>WPF RichTextBox Display</strong>:</p>
  <p><a href="https://i.stack.imgur.com/mU9Zo.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mU9Zo.jpg" alt="enter image description here" /></a></p>
  <p><strong>Code to get rtf</strong>:</p>
  <pre><code>string sRTF = &quot;&quot;;
  TextRange tr = new TextRange(rtbTest.Document.ContentStart, rtbTest.Document.ContentEnd);
  
  using (MemoryStream ms = new MemoryStream())
  {
      tr.Save(ms, DataFormats.Rtf);
      sRTF = ASCIIEncoding.Default.GetString(ms.ToArray());
  }
  
  Debug.Write(sRTF);
  </code></pre>
  <p><strong>RTF output</strong>:</p>
  <p>In the following output, We can see the rtf for the highlighted text <code>test</code> is <code>{\lang9\highlight2\ltrch test}</code>. How can we programmatically get the highlighted text (i.e. <code>test</code>) here. This is just an example., I mean to get all highlighted texts programmatically?</p>
  <pre><code>{\rtf1\ansi\ansicpg1252\uc1\htmautsp\deff2{\fonttbl{\f0\fcharset0 Times New Roman;}{\f2\fcharset0 Calibri;}}{\colortbl\red0\green0\blue0;\red255\green255\blue255;\red255\green255\blue0;}\loch\hich\dbch\pard\plain\ltrpar\itap0{\lang1033\fs18\f2\cf0 \cf0\ql{\fs22\f2 {\lang9\ltrch This is a }{\lang9\highlight2\ltrch test}{\lang9\ltrch  for a WPF RichTextBox}\li0\ri0\sa200\sb0\fi0\ql\par}
  {\f2 {\ltrch }\li0\ri0\sa0\sb0\fi0\ql\par}
  }
  }
  </code></pre>
  <p>Can we achieve the same programmatically in a WPF RichTextBox like we do (for example) in a WORD Document through a VBA macro shown below or through c# in a legacy VSTO add-in:</p>
  <pre><code>Selection.Find.ClearFormatting
  Selection.Find.Highlight = True
  With Selection.Find
      .Text = &quot;&quot;
      .Replacement.Text = &quot;&quot;
      .Forward = True
      .Wrap = wdFindContinue
      .Format = True
      .MatchCase = False
      .MatchWholeWord = False
      .MatchWildcards = False
      .MatchSoundsLike = False
      .MatchAllWordForms = False
  End With
  Selection.Find.Execute
  Selection.Find.Execute
  </code></pre>