Patrick Porter wrote:
Arrrgh!
I have tried everything (ok, not EVERYTHING) but i cant get solve the
problem of getting syntax highlighting in a rich textbox.
in the code below, im attempting to highlight all of the words "ax".
the matches works fine, but i cant get the highlighting to work
correctly. any help?
1) [the main point] Since you are going to be altering the Selection
details of your TextBox, you need to make sure you save what they were
before your changes, and restore them after you are done.
2) When I loaded up your code VS.NET immediately gave me wavy blue
underlines, and I saw that results() should be an Integer array; this
suggests you me you are running without Option Strict On. Running in
Strict mode is something you should consider making a permanent
situation. Yes, you have to make explicit all you implicit conversions.
This is generally thought to be a *good* thing :)
3) "ax" is two letters long so SelectionLength should be set to 2 not 3
before the colour is changed.
With those changes in mind here is your new routine:
Private Sub rtbCode_TextChanged(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles rtbCode.TextChanged
Dim SaveSelectionStart As Integer = rtbCode.SelectionStart
Dim SaveSelectionLength As Integer = rtbCode.SelectionLength
Dim SaveSelectionColor As Color = rtbCode.SelectionColor
Dim code As String = rtbCode.Text
Dim match As MatchCollection
Dim i As Integer
match = Regex.Matches(code, "ax")
Dim results(match.Count - 1) As Integer
For i = 0 To results.Length - 1
results(i) = match(i).Index
rtbCode.SelectionStart = match(i).Index
rtbCode.SelectionLength = 2
rtbCode.SelectionColor = Color.Blue
Next
rtbCode.SelectionStart = SaveSelectionStart
rtbCode.SelectionLength = SaveSelectionLength
rtbCode.SelectionColor = SaveSelectionColor
End Sub
It flickers a bit when run from the IDE, less so when run from the
executable. To avoid the flicker I suppose you would move to directly
manipulating the Rtf but this would be more work.
--
Larry Lard
Replies to group please