简体   繁体   English

如何将粗体文本添加到富文本框中

[英]How to add bold text to rich text box

I'm working with Visual Studio Express 2012 with C#. 我正在使用C#的Visual Studio Express 2012。

I am using code to add text to a RichTextBox . 我正在使用代码将文本添加到RichTextBox Each time there are 2 lines added. 每次添加2行。 The first line needs to be bold and the second line normal. 第一行需要加粗,第二行正常。

Here is the only thing I could think to try, even though I was sure it would not work: 这是我唯一能想到的东西,即使我确信它不会起作用:

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;

How can I add bolded lines to a rich text box? 如何将粗体线添加到富文本框?

Thanks for the answers submitted so far. 感谢到目前为止提交的答案。 I think I need to clarify a little. 我想我需要澄清一点。 I am not adding these 2 lines 1 time. 我没有添加这两行1次。 I will be adding the lines several times. 我将多次添加这些行。

In order to make the text bold you just need to surround the text with \\b and use the Rtf member. 为了使文本变粗,您只需要用\\b包围文本并使用Rtf成员。

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

OP mentioned that they will be adding lines over time. OP提到他们将随着时间的推移添加行。 If that is the case then this could be abstracted away into a class 如果是这种情况,那么这可以抽象成一个类

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

You can use the Rtf property of your RichTextBox . 您可以使用RichTextBox的Rtf属性。 First generate an rtf string: 首先生成一个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);

And append the string to the existing text in your RichTextBox : 并将字符串附加到RichTextBox的现有文本:

this.notes_pln.SelectionStart = this.notes_pln.TextLength;
this.notes_pln.SelectedRtf = rtf;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM