2012年12月1日 星期六

Richtextbox 搜尋字串並標示背景顏色

    Dim indexOfSearchText As Integer = 0
    Dim start As Integer = 0

    Private Sub search_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles search.Click
       
         Dim startindex As Integer

start_search:

        If TextBox1.Text.Length > 0 Then
            startindex = FindMyText(TextBox1.Text.Trim(), start, RichTextBox1.Text.Length)
        Else
            MsgBox("沒有關鍵字")
            GoTo mark_end
        End If

        ' If string was found in the RichTextBox, highlight it
        If startindex >= 0 Then
            ' Set the highlight color
            RichTextBox1.SelectionBackColor = Color.GreenYellow

            ' Find the end index. End Index = number of characters in textbox
            Dim endindex As Integer = TextBox1.Text.Length
            ' Highlight the search string
            RichTextBox1.Select(startindex, endindex)
            ' mark the start position after the position of
            ' last search string
            start = startindex + endindex
            GoTo start_search
        End If
mark_end:
    End Sub

    Public Function FindMyText(ByVal txtToSearch As String, ByVal searchStart As Integer, ByVal searchEnd As Integer) As Integer
        ' Set the return value to -1 by default.
        Dim retVal As Integer = -1

        ' A valid starting index should be specified.
        ' if indexOfSearchText = -1, the end of search
        If searchStart >= 0 AndAlso indexOfSearchText >= 0 Then
            ' A valid ending index
            If searchEnd > searchStart OrElse searchEnd = -1 Then
                ' Find the position of search string in RichTextBox
                indexOfSearchText = RichTextBox1.Find(txtToSearch, searchStart, searchEnd, RichTextBoxFinds.None)
                ' Determine whether the text was found in richTextBox1.
                If indexOfSearchText <> -1 Then
                    ' Return the index to the specified search text.
                    retVal = indexOfSearchText
                End If
            End If
        End If
        Return retVal
    End Function


改編自以下網址,感謝原作者。
http://www.dotnetcurry.com/ShowArticle.aspx?ID=146