2011-03-22 59 views
3

我想在我的richtextbox多色文本中创建一行文本。我尝试过在网络上提供的各种实现,并阅读SelectedText和其他主题,但似乎无法按照我想要的方式工作。vb.net - 多色RichTextBox

这里是我迄今为止

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]”为绿色,“黑色”为黑色。

回答

5

这是不是很清楚你想达到什么。我不确定我是否理解了括号内的格式,与我在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") 

结果将是这样的:

      sample RichTextBox with formatted text

+0

这正是我一直在寻找。非常感谢! – Phil 2011-03-23 00:05:28