改变标题RichTextBox VB.NET的颜色

时间:2017-06-17 21:46:26

标签: vb.net

我正在试验VB.NET 2010,我试图改变特定文本的颜色。

我创建了一个捕获当前Windows标题并在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的颜色发生变化,只想改变当前活动窗口标题的颜色:)

提前感谢所有评论!

1 个答案:

答案 0 :(得分:0)

所以,我认为你自己比你应该做的更难,你可以重写你的计时器逻辑,如下所示

 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