2011-03-22 84 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