如何在富文本框中添加加粗文本

5

我正在使用Visual Studio Express 2012和C#进行工作。

我正在使用代码向RichTextBox添加文本。每次添加两行。第一行需要加粗,第二行是普通的。

这是我能想到的唯一尝试,尽管我确信它不会起作用:

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次。我将会多次添加这些行。

2个回答

9

想要将文字加粗,只需用 \b 包围文本并使用 Rtf 成员。

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

提到过会不断添加行。如果是这样,那么可以将其抽象成一个类。

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 " + _builder.ToString() + @" }";
  }
}

谢谢您的回答。然而,似乎我无法使用此方法逐行添加文本。当我尝试使用“this.notes_pnl.Rtf + =”时,没有任何内容显示。 - Lee Loftiss
@LeeLoftiss 一旦您开始使用 rtf,您应该将其用于所有符号,包括换行符。 使用\line可打断行。 - JaredPar
谢谢。问题是我将在不同的时间添加多行代码,因此我需要将文本附加到先前的文本中。 - Lee Loftiss
@LeeLoftiss 修改了我的答案,描述了如何使用构建器类逐步构建行。 - JaredPar
感谢您的帮助,JaredPar。 - Lee Loftiss
2
公共字符串 ToRtf() { 返回 @"{\rtf1\ansi " + _builder.ToString() + @" }"; } - Exceptyon

4
您可以使用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;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接