[英]How to Append RTF Text in RichTextBox, Win C#
我在Win C#中有一個RichTextBox,我想在RichTextBox中附加一些帶有Bold效果的新文本。 那我怎么能這樣做呢。
我試過了
string str = richTextBox.Rtf;
//my logic
str+= @"\rtf1\ansi Adding Some \b Text\b0.}";
//
現在附加
richTextbox.AppendText(str);
但它沒有表現出正確的。
之前的輸出
這是第一句話。
我希望輸出像
這是第一句話。 添加一些文字 。
那我該怎么做呢?
以下函數引用了RichTextBox以及一些格式化參數。 該功能記錄在案:
/// <summary>
/// Append formatted text to a Rich Text Box control
/// </summary>
/// <param name="rtb">Rich Text Box to which horizontal bar is to be added</param>
/// <param name="text">Text to be appended to Rich Text Box</param>
/// <param name="textColour">Colour of text to be appended</param>
/// <param name="isBold">Flag indicating whether appended text is bold</param>
/// <param name="alignment">Horizontal alignment of appended text</param>
private void AppendFormattedText(RichTextBox rtb, string text, Color textColour, Boolean isBold, HorizontalAlignment alignment)
{
int start = rtb.TextLength;
rtb.AppendText(text);
int end = rtb.TextLength; // now longer by length of appended text
// Select text that was appended
rtb.Select(start, end - start);
#region Apply Formatting
rtb.SelectionColor = textColour;
rtb.SelectionAlignment = alignment;
rtb.SelectionFont = new Font(
rtb.SelectionFont.FontFamily,
rtb.SelectionFont.Size,
(isBold ? FontStyle.Bold : FontStyle.Regular));
#endregion
// Unselect text
rtb.SelectionLength = 0;
}
以下代碼添加原始文本:
這是第一句話。
// This creates the original text
AppendFormattedText(richTextBox, "This is ", Color.Black, false, HorizontalAlignment.Left);
AppendFormattedText(richTextBox, "First", Color.Black, true, HorizontalAlignment.Left);
AppendFormattedText(richTextBox, " Word.", Color.Black, false, HorizontalAlignment.Left);
...然后在最后添加一個句子,以便Rich Text Box的內容符合要求:
這是第一句話。 添加一些文字 。
// This appends additional text
AppendFormattedText(richTextBox, " Adding Some ", Color.Black, false, HorizontalAlignment.Left);
AppendFormattedText(richTextBox, "Text", Color.Black, true, HorizontalAlignment.Left);
AppendFormattedText(richTextBox, ".", Color.Black, false, HorizontalAlignment.Left);
除了問題中要求的內容之外還有其他參數(例如顏色),但這些參數構成了所有格式化操作的基礎,可以使用select-format-deselect方法進行格式化,而不是手動編輯RTF代碼。
假設插入點位於末尾(默認情況下),只需執行以下操作:
richTextBox1.SelectedRtf = @"{\\rtf1\\ansi Adding some \\b text\\b0.}";
雖然我已經看到很多使用剪貼板的例子,這是在Rich Text控件中任意位置插入圖像的絕佳方式(只需使用Rich Text控件的Paste()方法),最簡單的解決方案是簡單地將目標SelectionStart屬性放入它的TextLength屬性確保其SelectionLength屬性為零,然后將源的SelectedRtf屬性的內容填充到目標 - 現在為空的SelectedRtf。 當然,需要注意的是,您不應該嘗試將RTF屬性的全部內容插入到目標Rtf屬性中。 你只想要選擇。 有時候,我必須通過創建隱藏的Rich Text控件來完成此操作,填充其Rtf屬性並插入完整的RTF文本,調用其SelectAll方法以選擇我要插入的所有文本,然后插入RTB的SelectedRtf屬性為目標SelectedRtf屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.