【问题标题】:vb.net - Multicolor RichTextBoxvb.net - 多色 RichTextBox
【发布时间】:2011-07-20 22:19:29
【问题描述】:

我想在我的 Richtextbox 多色中制作一行文本。我尝试了网络上提供的各种实现,并阅读了 SelectedText 和其他主题,但似乎无法按照我想要的方式工作。

这是我目前所拥有的

RichTextBox1.Text = "This is black "
RichTextBox1.SelectionFont = New Font("Microsoft Sans Serif", 8.25, FontStyle.Bold)
RichTextBox1.SelectionColor = Color.Green
RichTextBox1.SelectedText = "[BOLD GREEN]"
RichTextBox1.Text = RichTextBox1.Text + " black again"

我想要的颜色以文字说明。发生的情况是:整行变为绿色,“[BOLD GREEN]”出现在文本框的开头而不是内联。

我希望它像这样读:“这是黑色的”为黑色。 “[BOLD GREEN]”为绿色,“再次变黑”为黑色。

【问题讨论】:

    标签: vb.net user-interface textbox richtextbox


    【解决方案1】:

    目前还不清楚您要达到的目标。我不确定我对括号格式的理解几乎与您在 Paint 中模拟的图像一样。但不管怎样……

    我怀疑您现有的代码存在一些问题。首先是插入新文本时光标的位置。由于插入标记所在的位置,第一个 sn-p 实际上被插入 before 它应该在 after 之后发生什么。要解决这个问题,您需要手动移动它。

    您还在代码末尾为Text 属性分配了一个文本字符串,这不会保留现有的格式信息。我怀疑你做的最简单的事情就是使用AppendText method

    最后,我建议使用simpler overload 来创建新字体,因为您唯一要更改的就是样式。使用它的好处是您不必在代码中硬编码字体的名称和大小,以防您以后想更改它。

    尝试改写你的代码:

    ' Insert first snippet of text, with default formatting
    RichTextBox1.Text = "This is black "
    
    ' Move the insertion point to the end of the line
    RichTextBox1.Select(RichTextBox1.TextLength, 0)
    
    'Set the formatting and insert the second snippet of text
    RichTextBox1.SelectionFont = New Font(RichTextBox1.Font, FontStyle.Bold)
    RichTextBox1.SelectionColor = Color.Green
    RichTextBox1.AppendText("[BOLD GREEN]")
    
    ' Revert the formatting back to the defaults, and add the third snippet of text
    RichTextBox1.SelectionFont = RichTextBox1.Font
    RichTextBox1.SelectionColor = RichTextBox1.ForeColor
    RichTextBox1.AppendText(" black again")
    

    结果将如下所示:

       

    【讨论】:

    • 这正是我想要的。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多