在Windows窗体中的RichTextBox中高亮显示文本

4
如何使输入 RichTextBox 中的某个词高亮显示?
如何查找文本中的单词以使用 SelectionColorSelectionFont
例如:我希望每次在RichTextBox中出现“hello”这个单词时,将其转换为粗体或改变颜色...
然后,如果我打开我的程序并输入“hello, how are you?”,则单词hello会变成粗体...有什么想法吗?(我的想法是制作一个具有语法高亮的文本编辑器,我将指定这些单词)
(如果有类似的问题,请见谅,我试图搜索但没有找到能帮助我的答案)
这是Windows Forms和Visual Basic。
5个回答

3
这段代码应该可以完成任务:
Dim searchstring As String = "hello"
' The word you're looking for
Dim count As New List(Of Integer)()
For i As Integer = 0 To richTextBox1.Text.Length - 1
    If richTextBox1.Text.IndexOf(searchstring, i) <> -1 Then
        'If the word is found
            'Add the index to the list
        count.Add(richTextBox1.Text.IndexOf(searchstring, i))
    End If
Next
Try
    For i As Integer = 0 To count.Count - 1

        richTextBox1.[Select](count(i), searchstring.Length)
        richTextBox1.SelectionFont = New Font(richTextBox1.Font, FontStyle.Bold)
        count.RemoveAt(i)
    Next
Catch
End Try
richTextBox1.[Select](richTextBox1.Text.Length, 0)
richTextBox1.SelectionFont = New Font(richTextBox1.Font, FontStyle.Regula

对于每个索引,选择文本并将其加粗。

现在将此代码添加到 TextChanged 事件中,以便检查任何时候文本是否更改为您的单词。


+1 但他要求使用VB,而且当更改单词时,光标会移到单词的开头。不过非常好。 - Hanlet Escaño

3

我用了不同的方式得到了它:

   While Not RichTextBox1.Text.IndexOf("hello", startIndex) = -1
               selectedIndex= RichTextBox1.SelectionStart
        Try
                RichTextBox1.Select(RichTextBox1.Text.IndexOf("test", startIndex) - 1, 1)
        Catch
        End Try
        If RichTextBox1.SelectedText = " " Or RichTextBox1.SelectedText = Nothing Then
            RichTextBox1.Select(RichTextBox1.Text.IndexOf("hello", startIndex) + "test".Length, 1)
            If RichTextBox1.SelectedText = " " Or RichTextBox1.SelectedText = Nothing Then
                RichTextBox1.Select(RichTextBox1.Text.IndexOf("hello", startIndex), "test".Length)
                RichTextBox1.SelectionColor = Color.Blue
            End If
        End If

        startIndex = RichTextBox1.Text.IndexOf("hello", startIndex) + "hello".Length
        RichTextBox1.SelectionStart = selectedIndex
        RichTextBox1.SelectionLength = 0
        RichTextBox1.SelectionColor = Color.Black
    End While

我不知道这是否是最好的方法,但它能够正常工作。


你确定它是这样工作的吗?我测试过了,不起作用。 我编辑了你的代码。 你不能将string添加到int中。还是很好的,所以+1。 - jAC
@JanesAbouChleih 是的,它正在正常工作,我不知道为什么对你没有起作用,我不确定你说它卡在哪里 :S - user1938775
看一下修改记录,你就能明白我说的“string”和“int”的意思了。链接:http://stackoverflow.com/posts/14470919/revisions 但是我会给你解释一下:“RichTextBox1.Text.IndexOf("test""hello", asdstartIndex).ToString() + "test""hello".Length ” 首先,.ToString()是一个方法,虽然在这种情况下不需要参数,但你还是需要括号。然后,你试图将IndexOf("test""hello", asdstartIndex).ToString()"hello".Length相加。这是行不通的:一个是“字符串”,另一个是“整数” - jAC
@JanesAbouChleih 嗯,看起来你是对的,但奇怪的是这段代码在我这里即使包含“.ToString()”也能工作,但我猜当“.ToString()”返回一个数字时它会被视为相同的数值? - user1938775

0

私有子 RichTextBox1_DragOver(sender As Object, e As DragEventArgs) Handles RichTextBox1.DragOver

    Dim p As Point
    p.X = e.X
    p.Y = e.Y
    Dim num As Integer
    Dim rightTXT As String
    Dim leftTXT As String
    Dim textpart As String
    Dim TSelect As Boolean
    Dim curpos As Integer = RichTextBox1.GetCharIndexFromPosition(RichTextBox1.PointToClient(p))
    Dim PosStart As Integer

    TSelect = False
    If e.Data.GetDataPresent(DataFormats.StringFormat) Then

        e.Effect = DragDropEffects.All

        Try
            leftTXT = Microsoft.VisualBasic.Left(RichTextBox1.Text, curpos)
            If InStr(leftTXT, "%", CompareMethod.Text) Then
                rightTXT = Microsoft.VisualBasic.Right(RichTextBox1.Text, Len(RichTextBox1.Text) - curpos)

                If InStr(rightTXT, "%", CompareMethod.Text) Then
                    PosStart = curpos - InStr(StrReverse(leftTXT), "%") + 1
                    num = curpos + InStr(rightTXT, "%") - PosStart - 1

                    textpart = (RichTextBox1.Text.Substring(PosStart, num).TrimEnd)

                    Label3.Text = "mouse drag over:" + textpart
                    Label5.Text = num.ToString()

                    If ListBox1.Items.Contains(textpart) Then
                        TSelect = True
                    End If
                End If
            End If
        Catch ex As Exception
            Label4.Text = ex.ToString()
        End Try

    End If

    If TSelect Then      
        Me.RichTextBox1.Select(PosStart - 1, num + 2)
        wordSearch = RichTextBox1.SelectedText

        Label4.Text = "word drag state: true"
        match = True   
    Else
        Label3.Text = "mouse drag over:"
        Label4.Text = "word drag state: false"
        Me.RichTextBox1.Select(0, 0)
    End If
End Sub

0

我觉得上面的代码对于一个简单的任务来说太冗长/复杂了...

    Dim c As Integer = 0

    Dim o As Integer = 0
    Dim s As Integer = 0

    Dim txt As String = RTB.Text
    RTB.BackColor = Color.Black

    Dim starts As Integer = 0

    Do While txt.Contains(key) ' this avoids unnecessary loops

        s = txt.IndexOf(key)
        starts = s + o
        RTB.Select(starts, key.Length)
        RTB.SelectionBackColor = Color.Yellow
        RTB.SelectionColor = Color.Blue

        txt = txt.Substring(s + key.Length)
        o += (s + key.Length)

        c += 1

    Loop
    Me.Status.Text = c.ToString() & " found" ' and the number found

0

这是一个用于在找到选定文本后将其突出显示为黄色(可以替换为任何其他颜色)的代码:

    'find the text that need to be highlighted.
    foundIndex = RichTextBox1.Find("hello", foundIndex + 1, -1, selectedFinds)
    RichTextBox1.Focus()

    If foundIndex = -1 Then
        MessageBox.Show("This document don't contains the text you typed, or any of the text you typed as a whole word or mach case.", "Find Text Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
 else
'now the text will be highlighted.
 RichTextBox1.SelectionBackColor = Color.Yellow
Richtextbox1.focus
    End If

我希望那段代码能够有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接