2014-01-19 208 views
4

我正在使用Visual Studio Express 2012与C#一起工作。如何将粗体文本添加到富文本框

我正在使用代码将文本添加到RichTextBox。每次添加2行。第一行需要大胆,第二行正常。

这是我能想到的尝试的唯一的事情,尽管我确信这是行不通的:

this.notes_pnl.Font = new Font(this.notes_pnl.Font, FontStyle.Bold); 
this.notes_pnl.Text += tn.date.ToString("MM/dd/yy H:mm:ss") + Environment.NewLine; 
this.notes_pnl.Font = new Font(this.notes_pnl.Font, FontStyle.Regular); 
this.notes_pnl.Text += tn.text + Environment.NewLine + Environment.NewLine; 

我如何粗线添加到丰富的文本框?

感谢迄今为止提交的答案。我想我需要澄清一点。 我不添加这2行1次。我会多次添加这些线。

回答

7

为了使文字变粗体,您只需围绕文本\b并使用Rtf成员。

this.notes_pln.Rtf = @"{\rtf1\ansi this word is \b bold \b0 }"; 

OP提到他们将随着时间的推移添加线。如果是这样的话,那么这可以被抽象出来成一个类

class RtfBuilder { 
    StringBuilder _builder = new StringBuilder(); 

    public void AppendBold(string text) { 
    _builder.Append(@"\b "); 
    _builder.Append(text); 
    _builder.Append("\b0 "); 
    } 

    public void Append(string text) { 
    _builder.Append(text); 
    } 

    public void AppendLine(string text) { 
    _builder.Append(text); 
    _builder.Append(@"\line"); 
    } 

    public string ToRtf() { 
    return @"{\rtf1\ansi " + ToString() + @" }"; 
    } 
} 
+0

感谢您的回答。但是,看来我无法一次追加1行。当我尝试'this.notes_pnl.Rtf + ='时不显示任何内容。 –

+0

@LeeLoftiss一旦你开始使用'rtf',你应该使用它包括换行符在内的所有符号。使用'\ line'应该破坏行 – JaredPar

+0

谢谢。问题是我会在不同的时间添加几行,所以我需要将文本追加到前面的文本中。 –

2

您可以使用RichTextBox的RTF财产。首先生成一个RTF字符串:

var rtf = string.Format(@"{{\rtf1\ansi \b {0}\b0 \line {1}\line\line }}", 
          tn.date.ToString("MM/dd/yy H:mm:ss"), 
          tn.text); 

和字符串追加到现有的文本在您的RichTextBox

this.notes_pln.SelectionStart = this.notes_pln.TextLength; 
this.notes_pln.SelectedRtf = rtf; 
相关问题