Hello All!
So, just like a lot of others, I thought I'd try my hand at colorizing keywords. Not that I need it for anything serious... just figured it would be fun to try... and so far it has been fun!
Anyways, what I have works pretty good. However, I'm wondering if there is any way to speed things up a bit.
Keep in mind... I am a beginner at this so I may be doing something wacko! If I did, please let me know.
So, what I have is an inherited richtextbox with the following code:
Private Sub ColorizePastedText()
Dim CursorPosition As Integer = Me.SelectionStart
Dim RegXMatches As MatchCollection
Dim RegXMatch As Match
Dim tmpRTB As New RichTextBox
'LastRTBLength is the Textlength before the paste. RTB TextLength stored on key down event
Dim PasteLength As Integer = Me.TextLength - LastRTBLength
'Get rid of the RTB flickering
LockWindowUpdate(Me.Handle.ToInt32)
tmpRTB.Rtf = Me.Rtf
tmpRTB.SelectAll()
tmpRTB.SelectionFont = Me.Font
'Find keywords then colorize them
For Each KeyWord In KeywordList
RegXMatches = System.Text.RegularExpressions.Regex.Matches(tmpRTB.Text, "\b" & KWord & "\b")
For Each RegXMatch In RegXMatches
If RegXMatch.Index >= LastCurPos AndAlso RegXMatch.Index < LastCurPos + PasteLength Then 'Colorize only what was just pasted
tmpRTB.Select(RegXMatch.Index, RegXMatch.Length)
tmpRTB.SelectionColor = KeywordColor
End If
Next
Next
Me.Rtf = tmpRTB.Rtf
'Put the cursor back where it started from
Me.SelectionStart = CursorPosition
'Set the RichTextBox's color back to normal
Me.SelectionColor = Me.ForeColor
'Unlock RichTextBox
LockWindowUpdate(0)
End Sub
The idea is that it will colorize keywords that are newly pasted and ignore anything that was already in the RTB.
If I copy a hundred or so lines of text then paste it into the RTB it processes the text within a reasonable amount of time. However, if I past the same text again it takes a bit longer to process. The process time continues to increase with each additional paste.
I know I lose a tiny bit of time in transferring the rtf data as it is larger, but the real loss is in the "For" statement. If I throw in
"tmpRTB.Select()" right after "tmpRTB.SelectionColor = KeywordColor" It will select what was pasted... telling me that it is working within only the pasted area.
I'm sure it's something simple... I'm just not seeing it.! :)
Any ideas will be greatly appreciated!
Thanks!