vb.net - 多色RichTextBox

Phi*_*hil 4 vb.net user-interface textbox 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"
Run Code Online (Sandbox Code Playgroud)

我想要的颜色是文字.会发生什么:整行变为绿色,"[BOLD GREEN]"出现在文本框的开头而不是内联.

我希望它像这样读:"这是黑色的"黑色."[BOLD GREEN]"为绿色,"black again"为黑色.

Cod*_*ray 5

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

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

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

最后,我建议使用更简单的重载来创建一个新字体,因为你唯一想要改变的是样式.使用它的优点是您不必在代码中硬编码字体的名称和大小,以防您以后想要更改它.

请尝试将代码重写为此代码:

' 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")
Run Code Online (Sandbox Code Playgroud)

结果将如下所示:

   示例带有格式化文本的RichTextBox