富文本框中的简单文本颜色

时间:2009-11-05 21:31:06

标签: vb.net richtextbox colors

我可以找到一百万个使用reg ex将语法高亮显示应用于富文本框的示例。但我需要它只是一个简单的方法来添加一个不同颜色的单词。

将代码“Hello World”放入文本框并将Hello设为红色且World为绿色是什么代码?

此代码无效。

this.richTextBox1.SelectionColor = Color.Red
this.richTextBox1.text += "Test"

6 个答案:

答案 0 :(得分:7)

将其放入后选择文字,然后更改颜色。

例如:

richTextBox1.Text += "Test"
richTextBox1.Select(richTextBox1.TextLength - 4, 4)
richTextBox1.SelectionColor = Color.Red

答案 1 :(得分:7)

此代码将红色文本“Hello”和RichTextBox中的“World”绿色添加。

RichTextBox1.SelectionColor = Color.Red
RichTextBox1.SelectedText = "Hello "
RichTextBox1.SelectionColor = Color.Green
RichTextBox1.SelectedText = "World"

答案 2 :(得分:2)

我在VB6中使用过它,我认为它是一样的: 您必须选择文本然后应用

this.richTextBox1.SelectionColor = Color.Red

添加的文本始终以defaut颜色显示,您必须选择它然后更改其颜色:

this.richTextBox1.text="Hello world!"
this.richTextBox1.selstart=0
this.richTextBox1.sellength=5
this.richTextBox1.SelectionColor = Color.Red

由于我不使用vb​​.net,你必须检查拼写,但我认为这是关键。 我写的代码应该用红色和“世界”打印“Hello”。黑色。

答案 3 :(得分:1)

试试这个

    RichTextBox2.SelectionLength = 0
    RichTextBox1.SelectionStart = 0
    ' We deselect everything first in case the user has something selected.
    RichTextBox1.SelectionColor = Color.Red
    RichTextBox1.SelectedText = "Hello "
    RichTextBox1.SelectionColor = Color.Green
    RichTextBox1.SelectedText = "World "

这会将其添加到文本框的开头。我想你也可以使SelectionStart = RichTextBox1.TextLength将它放在最后而不是开头。

答案 4 :(得分:0)

代码不起作用:

this.richTextBox1.SelectionColor = Color.Red
this.richTextBox1.text += "Test"

将第二行更改为:

this.richTextBox1.SelectionColor = Color.Red
this.richTextBox1.selectedtext = "Test"

答案 5 :(得分:0)

试试这个

Sub colorWord(ByVal word As String, ByVal color As Color) ' by im4dbr0
        For i As Integer = 0 To RichTextBox1.TextLength
            Try
                If RichTextBox1.Text.ElementAt(i).ToString = word.ElementAt(0).ToString Then
                    Dim found As Boolean = False
                    For j As Integer = 1 To word.Count - 1
                        If RichTextBox1.Text.ElementAt(i + j) = word.ElementAt(j) Then
                            found = True
                        Else
                            found = False
                            Exit For
                        End If
                    Next
                    If found = True Then
                        RichTextBox1.Select(i, word.Length)
                        RichTextBox1.SelectionColor = color
                    End If
                End If
            Catch ex As Exception
                Continue For
            End Try
        Next

对于多个单词,请使用循环

 Dim Words As New List(Of String)
        Words.Add("Its")
        Words.Add("That")
        Words.Add("Simple")
        For i As Integer = 0 To Words.Count - 1
            colorWord(Words.Item(i), Color.Red)
        Next
相关问题