簡體   English   中英

富文本框中的簡單文本顏色

[英]simple text color in rich text box

我可以找到一百萬個使用reg ex將語法高亮顯示應用於富文本框的示例。 但我需要它只是一個簡單的方法來添加一個不同顏色的單詞。

將代碼“Hello World”放入文本框並將Hello設為紅色且World為綠色是什么代碼?

這段代碼不起作用。

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

將其放入后選擇文本,然后更改顏色。

例如:

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

此代碼將紅色文本“Hello”和RichTextBox中的“World”綠色添加為綠色。

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

我已經在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”。 黑色。

嘗試這個

    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將它放在最后而不是開頭。

代碼不起作用:

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

將第二行更改為:

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

嘗試這個

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM