【问题标题】:Change forecolor of a certain line in RichTextBox, if it contains certain text更改 RichTextBox 中某行的前景色,如果它包含某些文本
【发布时间】:2014-01-24 06:33:50
【问题描述】:

这可能是一个简单的答案,但目前我还没有想到。 我的程序打开一个文件并且该文件确实包含 cmets,我想将“//”之后的所有文本都设为绿色。

我正在尝试做的是这样的事情:(这与在 VB.Net 中评论的方式完全相同,但使用 ')

If rtb.contains("//") Then
   'make the text after '//' green
End If

【问题讨论】:

  • 您的意思是如何在文本框控件中执行此操作?如果您使用的是 Windows 窗体,那么下面的链接将为您提供答案。 stackoverflow.com/questions/2527700/…
  • @ShadowLiberal 嗯,不完全是。你知道如果你在 c# 中输入“//this now is a comment”并且//之后的文本变成绿色(包括//),这就是我要为我的程序做的事情。

标签: vb.net winforms richtextbox


【解决方案1】:

假设现有文本,您可以运行 Lines 数组来检查文本:

For i As Integer = 0 To RichTextBox1.Lines.Length - 1
  Dim s As String = RichTextBox1.Lines(i)
  Dim index As Integer = s.IndexOf("//")
  If index > -1 Then
    Dim length As Integer = s.Length - index
    index += RichTextBox1.GetFirstCharIndexFromLine(i)
    RichTextBox1.Select(index, length)
    RichTextBox1.SelectionColor = Color.Green
  End If
Next
RichTextBox1.Select(0, 0)

【讨论】:

  • 这里需要在索引后面加上不带引号的“+2”:RichTextBox1.Select(index +2, length) 来满足OP的要求。
  • @SomeNickName 通常斜线与注释的颜色相同。请参阅上面 OP 对 ShadowLiberal 的评论:(including the //)
  • 哦,对不起,没看到......那么你的解决方案是完美的:p
【解决方案2】:

您使用的是文本框吗?如果是这样,您需要使用 RichTextbox 来做您想做的事情。 像这样:

'设置选择开始字符 '设置selecionstart字符后选中字符的个数 '设置选择颜色

编辑:哦,你想在“\\”字符之后,误读,使用我认为的@LarsTech 答案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-13
    • 1970-01-01
    • 2011-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多