Rich Text parsing with RichTextBox




I have some rich text strings saved in a database that I need to
convert to another format. I need to extract information like font and
color from the RTF strings. So I thought that I would just get a
RichTextBox and use it to interpret the RTF text for me, but the
RichTextBox doesn't seem to be able to understand my RTF. For example,
it tells me the color is always Color.Empty and the font is null, even
if I set them myself. The RTF text was originally created with VB6.0's
rich text control.

The documentation says that if the color changes in a selection, then
SelectionColor() returns Color.Empty. But it returns Color.Empty even
if I select a single character. How can a single character have a color
change? Then I set all the text to green just as a test, but
SelectionColor still returns Color.Empty.

Here's some C# code that shows the strange behavior:
string rtf =
MS Sans Serif;}}\r\n{\\*\\generator Riched20;}\\viewkind4\\uc1\\pard\\f0\\fs24 Here is some sample rich

RichTextBox rtb = new RichTextBox();
rtb.Rtf = rtf;
rtb.Select(0, 1); // Select the first character.
if (rtb.SelectionColor == Color.Empty) {
// How can a single character have a color change?
rtb.Select(0, rtb.Text.Length - 1); // Select everything.
rtb.SelectionColor = Color.Green; // Make everything green.
Console.WriteLine("Color: " + rtb.SelectionColor.ToString());

The code always writes "Color: Color [Empty]". The behavior is similar
when I work with SelectionFont.

I may be using the RichTextBox wrong, or the RTF strings may have a bad
format, or the RichTextBox may not operate correctly until it is placed
on a form. Can anyone tell me why the RichTextBox doesn't seem to work
with my rich text? Or is there some other tool I can use to parse rich

Thanks for your help.

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question