简体   繁体   中英

Inability to properly load Rtf to a RichTextBox

I have a custom RichTextBox that derives from the RichTextBox base class. Its purpose is to display formatted text. However, any Rtf loaded is displayed as simple text without any formatting: font, font-size, font-style etc.

I have tried the following code to load the Rtf: (Note: rtbEx is the extended richtextbox control; RTF is a string containing the Rtf)

  1. Using a file stream:

     FileStream tempFile = File.Open(@"C:\\RTF.rtf", FileMode.Open); tempFile.Position = 0; rtbEx.LoadFile(tempFile, RichTextBoxStreamType.RichText); tempFile.Close();
  2. Loading from the specified path:

     rtbEx.LoadFile(@"C:\\Users\\Wilbur Omae\\Desktop\\RTF.rtf", RichTextBoxStreamType.RichText);
  3. Directly setting the Rtf:

     rtbEx.Rtf = RTF;

On checking the Rtf of the rtbEx, it seems to be perfect Rtf, yet it is displayed as plain text.

What could be the issue?

Update 1: The custom RichTextBox is a control within a custom Form which it to be displayed as a TabPage.

you can use Clipboard in this case :

 Clipboard.SetText(RichTextBox1.Rtf, TextDataFormat.Rtf);

and paste it

 RichTextBox1.Text= Clipboard.GetText()

It works for me .. try it

As a workaround, I ensured the Rtf was set only when the form had been shown by trapping the Form.Shown event as shown below:

public class SermonReader : Form
{
    public RichTextBoxEx rtbEx= new RichTextBoxEx();
    private string RTF = "";

    public SermonReader(string rtf)
    {
        RTF = rtf;

        Shown += new EventHandler(ehFormShown);
        FormBorderStyle = FormBorderStyle.None;
        TopLevel = false;

        Controls.Add(rtbEx);

        rtbEx.Dock = DockStyle.Fill;
    }
    private void ehFormShown(object sender, EventArgs e)
    {
        rtbEx.Rtf = RTF;
    }
}

I don't know why the issue is this complicated but I hope this helps.

Any other solution? Feel free to comment or answer.

I had the same problem with a richtextbox within a winformscontrol within a dialog (MFC), the rtb should be filled with rtf, but after setting RichTextBox.Rtf, loading from file or Clipboard it all was unformatted. I could solved it by using Postmessage in OnInitDialog with UpdataData(FALSE) (Sets RichTextBox.Rtf again) in the handler. seems as if creation yet was not complete ..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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