分享
三行代码  ›  专栏  ›  技术社区  ›  Ally

在中搜索时突出显示文本运动模拟

  •  1
  • Ally  · 技术社区  · 1 周前

    嗨,所以我创建了一个带有按钮、文本框和富文本框的搜索系统,用于搜索显示在富文本框(从文本文件导入)中的项目,并在找到时高亮显示它们。由于某些原因,当我单击“搜索”按钮时,它不会突出显示正在搜索的单词。

    这是我使用的代码:

        Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click  
    
        Dim index As Integer  = 0
    
          While index < rtxtEdit.Text.LastIndexOf(txtSearch.Text)  
            rtxtEdit.Find(txtSearch.Text,index ,rtxtEdit.TextLength, RichTextBoxFinds.None)  
            rtxtEdit.SelectionBackColor = Color.Red  
            index = rtxtEdit.Text.IndexOf(txtSearch.Text, index) + 1  
          End While  
        End Sub  
    
    3 回复  |  直到 1 周前
        1
  •  0
  •   Idle_Mind    1 周前

    我应该这样写:

    Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
        Dim searchFor As String = txtSearch.Text.Trim
        If searchFor <> "" Then
            Dim index As Integer = 0
            Dim startAt As Integer = 0
            Do
                index = rtxtEdit.Find(searchFor, startAt, RichTextBoxFinds.None)
                If index <> -1 Then
                    rtxtEdit.SelectionBackColor = Color.Red
                    startAt = index + 1
                End If
            Loop While index <> -1
        End If
    End Sub
    
        2
  •  0
  •   ROUBINSKI    1 周前

    post :

    Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
    Dim len = searchText.Length
    Dim pos = rtb.Find(searchText, 0, RichTextBoxFinds.NoHighlight)
    While (pos >= 0)
        rtb.Select(pos, len)
        rtb.SelectionBackColor = Color.Yellow
        if pos + len  >= rtb.Text.Length Then
            Exit While
        End If
        pos = rtb.Find(searchText, pos + len, RichTextBoxFinds.NoHighlight)
    End While
    End Sub
    
        3
  •  0
  •   user1855085    1 周前
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim index As Integer = 0
    
        'Clears the existing formatting
        Dim t = rtxtEdit.Text
        rtxtEdit.Text = t
    
        'Incremented the loop condition by 1 so that text at the beginning gets selected as well.
        While index < rtxtEdit.Text.LastIndexOf(txtSearch.Text) + 1
            rtxtEdit.Find(txtSearch.Text, index, rtxtEdit.TextLength, RichTextBoxFinds.None)
            rtxtEdit.SelectionBackColor = Color.Red
            index = rtxtEdit.Text.IndexOf(txtSearch.Text, index) + 1
        End While
    End Sub