【问题标题】:Change text colour in a TextBox upon condition根据条件更改文本框中的文本颜色
【发布时间】:2014-10-22 03:22:36
【问题描述】:

当文本等于某物时,我需要在富文本框中更改一个单词的颜色,例如,如果用户输入“Pink”,则文本将为粉红色,但只有单词 pink。

如何做到这一点?

【问题讨论】:

  • 如果您使用的是 Winforms,您可以选择文本框文本的一部分并将更改应用于所选内容。

标签: .net vb.net text colors richtextbox


【解决方案1】:

正如@Kilazur 在他/她的评论中所说,您需要选择单词并设置SelectionColor

这是一个例子:

Dim word As String = "word"
Dim index As Integer = Me.RichTextBox1.Text.IndexOf(word)

Do While (index > -1)
    Me.RichTextBox1.Select(index, word.Length)
    Me.RichTextBox1.SelectionColor = Color.Pink
    index = Me.RichTextBox1.Text.IndexOf(word, (index + word.Length))
Loop

【讨论】:

  • 您的代码将只检查一种颜色,因此如果输入了更多颜色,它不会提供更好的解决方案。
  • 我的英文不好不知道怎么解释,所以我试试看。 1. 您必须指定必须应用此代码的位置。 2.它不会给出问题的完整解决方案
  • @Sample 我不是来评判你的英语的。 1.) 不,我没有。如果这是问题的一部分和/或我会在问题中说明。它不是。 2.) OPs问题的关键是如何“改变富文本框中一个词的颜色”。我的回答说明了如何。
【解决方案2】:

选择感兴趣的文字后,可以使用SelectionColor属性。

您可以随时查找文本,但 TextChanged 事件似乎是一个很好的时机(尽管如果您有很多文本可能会很慢)

Private Sub RichTextBox1_TextChanged(sender As Object, e As EventArgs) Handles RichTextBox1.TextChanged
    FindWords(RichTextBox1, "Pink", Color.Pink)
End Sub

Private Sub FindWords(rtb As RichTextBox, word As String, wordColour As Color)
    'store the selection before any change was made so we can set it back later
    Dim selectionStartBefore As Integer = rtb.SelectionStart
    Dim selectionLengthBefore As Integer = rtb.SelectionLength

    Dim selection As Integer
    'loop through finding any words that match
    selection = rtb.Text.IndexOf(word)
    Do While selection >= 0
        rtb.SelectionStart = selection
        rtb.SelectionLength = word.Length
        rtb.SelectionColor = wordColour
        selection = rtb.Text.IndexOf(word, selection + word.Length)
    Loop

    'put the selection back to what it was
    rtb.SelectionStart = selectionStartBefore
    rtb.SelectionLength = selectionLengthBefore
    rtb.SelectionColor = rtb.ForeColor
End Sub

【讨论】:

    猜你喜欢
    • 2021-01-09
    • 2022-07-21
    • 2018-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-12
    相关资源
    最近更新 更多