【问题标题】:Changing color of a title RichTextBox VB.NET更改标题 RichTextBox VB.NET 的颜色
【发布时间】:2017-11-20 10:28:45
【问题描述】:

我在 VB.NET 2010 上进行试验,并试图更改特定文本的颜色。

我创建了一个捕获当前窗口标题并在 RichTextBox 中实现的计时器:

   Private Sub Timer3_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles activetitle.Tick
    If strin <> GetActiveWindowTitle() Then       
        RichTextBox1.Text = RichTextBox1.Text & vbNewLine & vbNewLine & "[---" & GetActiveWindowTitle() & "---]") & vbNewLine & vbNewLine
        strin = GetActiveWindowTitle()
    End If
End Sub

但是,我尝试更改代码,以便当当前活动标题保存在 RichTextBox 中时,它会以不同的颜色显示:

     Private Sub Timer3_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles activetitle.Tick
    If strin <> GetActiveWindowTitle() Then
        RichTextBox1.Text = RichTextBox1.Text & vbNewLine & vbNewLine & "[---" & GetActiveWindowTitle() & "---]" & vbNewLine & vbNewLine
        strin = GetActiveWindowTitle()
    End If
    If RichTextBox1.Text.Contains("[---" & "---]") Then
        RichTextBox1.SelectionColor = Color.Red
    End If
End Sub

我尝试了许多不同的变化,并在互联网上到处寻找,但没有成功:(

有谁知道如何更改在 RichTextBox 中实现的当前活动窗口标题的颜色?

我想提醒你,我不想改变整个 RichTextBox 的颜色,而只改变当前活动窗口标题的颜色 :)

在此先感谢所有 cmets!

【问题讨论】:

  • 您正在设置SelectionColor 属性,但似乎忘记在更改颜色之前设置SelectionStartSelectionLength
  • 那么我应该如何根据那个来修改这段代码呢?
  • 找到要着色的文本在文本框中的位置并将该位置设置为 SelectionStart,然后将 SelectionLength 属性的长度设置为要着色的文本的长度,然后应用选择颜色
  • 感谢您的回复 :) 问题是我的 Richtextbox 不断变化,因为它记录了我进行的活动窗口标题,因此位置总是不同的。是否有其他代码可以更改“[---”“---]”的颜色?
  • 我还是有点不确定你想涂什么颜色,什么时候涂,因为从我看到的代码中,你只会看到下一个活动窗口的颜色变化,之后没有活动标题。此外,RichTextBox 有一个名为 AppendText() 的方法可能更好地使用它

标签: vb.net


【解决方案1】:

所以,我认为你自己做的比你应该做的要困难得多,你可以像下面这样重写你的计时器逻辑

 Private Sub Timer3_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles activetitle.Tick
    If strin <> GetActiveWindowTitle() Then
        Dim oldColor = RichTextBox1.SelectionColor
        ' save the title first
        strin = GetActiveWindowTitle()
        ' set the cursor at the end (to be sure)
        RichTextBox1.SelectionStart = RichTextBox1.Length
        ' check if the text is empty
        If String.IsNullOrWhiteSpace( strin ) Then
            ' if yes, set the color to red
            RichTextBox1.SelectionColor = Color.Red
        End If
        ' add the new text to the RichTextBox
        RichTextBox1.AppendText(Environment.NewLine & "[---" & strin & "---]" & Environment.NewLine)
        ' revert to the previous selectioncolor
        RichTextBox1.SelectionColor = oldColor
    End If
End Sub

【讨论】:

  • Ty 回复但未成功 :( 还有其他内容添加到我的文本框中,因此它不仅仅是复制到其中的标题。我尝试了您的代码,但这就是我的得到 gyazo.com/e80a95f31eb08de460428b795fb40168
  • @EricCartman 我只能看到你现在有一些红色的东西,我从你的问题中可以看出你的意图。所以我不确定你的问题仍然是什么,你能用更多信息更新你的问题吗?
  • 抱歉不清楚 - 图片显示我记录的标题中只有 1 个是红色的,但我希望所有标题都涂成红色。但我不希望我的键盘记录是红色的(如果你看到我说的是“记事本”)。总体:除了我写的以外,一切都是红色的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-06
  • 2016-09-01
  • 1970-01-01
  • 2014-03-13
  • 2019-04-27
  • 1970-01-01
相关资源
最近更新 更多