この汎用関数を使用して、RichTextBox に「FindNext」機能を追加しました。
#Region " FindNext In RichTextBox "
' [ FindNext In RichTextBox Function ]
'
' //By Elektro H@cker
'
' Examples :
'
' RichTextBox1.Text = "Hello World!, Hello World!, Hello World!"
' FindNext(RichTextBox1, "Hello")
' FindNext
Private Sub FindNext(ByVal [Control] As RichTextBox, _
ByVal SearchText As String, _
Optional ByVal Highlight_BackColor As Color = Nothing, _
Optional ByVal Highlight_ForeColor As Color = Nothing)
' Start searching at 'SelectionStart'.
Dim Search_StartIndex As Integer = [Control].SelectionStart
Static Next_Count As Integer = 0
' Restore Highlight colors of previous selection
[Control].SelectionBackColor = [Control].BackColor
[Control].SelectionColor = [Control].ForeColor
' Set next selection Highlight colors
If Highlight_BackColor = Nothing Then Highlight_BackColor = [Control].BackColor
If Highlight_ForeColor = Nothing Then Highlight_ForeColor = [Control].ForeColor
' If is not first FindNext call then...
If Next_Count <> 0 Then
Search_StartIndex += SearchText.Length
Else ' If is first FindNext call then...
Next_Count += 1
End If
' Set Search_StartIndex
Search_StartIndex = _
[Control].Find(SearchText, Search_StartIndex, RichTextBoxFinds.NoHighlight Or RichTextBoxFinds.None)
' ...And prevent search at End Of File
If Search_StartIndex = -1 Then
Search_StartIndex = _
[Control].Find(SearchText, 0, RichTextBoxFinds.NoHighlight Or RichTextBoxFinds.None)
End If
' Set the match selection
[Control].Select(Search_StartIndex, SearchText.Length)
' Set the BackColor
[Control].SelectionBackColor = Highlight_BackColor
' Set the ForeColor
[Control].SelectionColor = Highlight_ForeColor
' Scroll to Caret/Cursor position
[Control].ScrollToCaret()
End Sub
#End Region
「前を検索」関数をどのようにコーディングしますか?
RegEx MatchCollection を使用して、コレクションの現在の RegEx 一致インデックスをシフトすることで「次を検索」または「前を検索」を簡単に追加できると思いますが、正規表現は遅いです。単純な文字列検索を使用する他の方法がありますか?