如何将RTF字符串输入到RichTextBox控件?

7
我有一串富文本字符/标记,我想在代码中将其传递给一个富文本框。
string rt  = @" {\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fswiss\fcharset0     Arial;}{\f1\fnil\fprq2\fcharset0 Biondi;}}"+
@"{\colortbl ;\red255\green0\blue0;}"+
@"{\*\generator Msftedit 5.41.15.1507;}\viewkind4\uc1\pard\f0\fs20\par"+
@"\cf1\f1 hello\cf0\f0  \ul world\par}";

我尝试过这个:
      System.IO.MemoryStream strm = new System.IO.MemoryStream();
      byte[] b = Encoding.ASCII.GetBytes(rt);
      strm.BeginRead(b, 0, b.Length, null, null);

      richTextBox1.LoadFile(strm, RichTextBoxStreamType.RichText);

它没有起作用。

有人能给我一些建议吗?

顺便说一下,这个富文本来自于在wordpad中保存,用notepad打开文件并使用其中的文本来构建我的字符串。

2个回答

13

富文本框具有名为 Rtf 的属性。将该属性设置为您的字符串值。此外,您的字符串以额外的空格作为第一个字符。在我看到你的“Hello World”之前,我不得不将其删除。


5
扩展gbogumil的回答:
string rt  = @"{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fswiss\fcharset0     Arial;}{\f1\fnil\fprq2\fcharset0 Biondi;}}"+
@"{\colortbl ;\red255\green0\blue0;}"+
@"{\*\generator Msftedit 5.41.15.1507;}\viewkind4\uc1\pard\f0\fs20\par"+
@"\cf1\f1 hello\cf0\f0  \ul world\par}";

this.richTextBox1.Rtf = rt;

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