vb.net – 多色RichTextBox

我想在我的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]”为绿色,“black again”为黑色.

你想要实现的目标并不是很清楚.我不确定我理解括号格式几乎和我在Paint中嘲笑的图像一样.但无论如何……

我怀疑你现有的代码存在一些问题.首先是插入新文本时光标的位置.由于插入标记所在的位置,第一个片段实际插入之前应该会发生什么.要解决此问题,您需要手动移动它.

您还要在代码末尾的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")

结果将如下所示:

相关文章

Format[$] ( expr [ , fmt ] ) format 返回变体型 format$ 强...
VB6或者ASP 格式化时间为 MM/dd/yyyy 格式,竟然没有好的办...
在项目中添加如下代码:新建窗口来显示异常信息。 Namespace...
转了这一篇文章,原来一直想用C#做k3的插件开发,vb没有C#用...
Sub 分列() ‘以空格为分隔符,连续空格只算1个。对所选...
  窗体代码 1 Private Sub Text1_OLEDragDrop(Data As Dat...