title: VB.NET Syntax Highlighting in a Rich Text Box
body: <p>I'm coding a simple code editor for a very simple scripting language we use at work. My syntax highlighting code works fine if I do it on the entire <code>RichTextBox</code> (<code>rtbMain</code>) but when I try to get it to work on just that line, so I can run the function with <code>rtbMain</code> changes, it gets weird. I can't seem to figure out why. Am I even going about this the right way?</p>
  
  <p><code>rtbMain</code> is the main text box.
  <code>frmColors.lbRegExps</code> is a listbox of words to highlight (later it will have slightly more powerful regular expressions.)
  <code>frmColor.lbHexColors</code> is another listbox with the corresponding hex colors for the words.</p>
  
  <pre><code>Private Sub HighLight(ByVal All As Boolean)
      Dim RegExp As System.Text.RegularExpressions.MatchCollection
      Dim RegExpMatch As System.Text.RegularExpressions.Match
      Dim FirstCharIndex As Integer = rtbMain.GetFirstCharIndexOfCurrentLine
      Dim CurrentLine As Integer = rtbMain.GetLineFromCharIndex(FirstCharIndex)
      Dim CurrentLineText As String = rtbMain.Lines(CurrentLine)
      Dim CharsToCurrentLine As Integer = rtbMain.SelectionStart
      Dim PassNumber As Integer = 0
  
      LockWindowUpdate(Me.Handle.ToInt32) 'Let's lock the window so it doesn't scroll all crazy.
      If All = True Then 'Highlight everything.
          For Each pass In frmColors.lbRegExps.Items
              RegExp = System.Text.RegularExpressions.Regex.Matches(LCase(rtbMain.Text), LCase(pass))
              For Each RegExpMatch In RegExp
                  rtbMain.Select(RegExpMatch.Index, RegExpMatch.Length)
                  rtbMain.SelectionColor = ColorTranslator.FromHtml(frmColors.lbHexColors.Items(PassNumber))
              Next
              PassNumber += 1
          Next
      Else 'Highlight just that row.
          For Each pass In FrmColors.lbRegExps.Items
              RegExp = System.Text.RegularExpressions.Regex.Matches(LCase(CurrentLineText), LCase(pass))
              For Each RegExpMatch In RegExp
                  rtbMain.Select(RegExpMatch.Index + (CharsToCurrentLine - RegExpMatch.Length), RegExpMatch.Length)
                  rtbMain.SelectionColor = Color.Blue
              Next
          Next
      End If
  
      rtbMain.Select(CharsToCurrentLine, 0) 'Reset colors and positon and then unlock drawing.
      rtbMain.SelectionColor = Color.Black
      LockWindowUpdate(0)
  End Sub
  </code></pre>