BKimmel
BKimmel

Reputation: 611

Better Way of Manipulating RichText in C#?

I need to create and copy to the clipboard some RichText with standard "formatting" like bold/italics, indents and the like. The way I'm doing it now seems kind of inelegant... I'm creating a RichTextBox item and applying my formatting through that like so:

RichTextBox rtb = new RichTextBox();
Font boldfont = new Font("Times New Roman", 10, FontStyle.Bold);
rtb.Text = "sometext";
rtb.SelectAll()
rtb.SelectionFont = boldfont;
rtb.SelectionIndent = 12;

There has got to be a better way, but after a few hours of searching I was unable to come up with anything better. Any ideas?

Edit: The RichTextBox (rtb) is not displayed/drawn anywhere on a form. I'm just using the object to format my RichText.

Upvotes: 5

Views: 8996

Answers (6)

ePandit
ePandit

Reputation: 3243

You should also suspend the layout of the richtextbox just after creation and dispose it after use.

RichTextBox rtb = new RichTextBox();
rtb.SuspendLayout();
//richtext processing goes here...
rtb.Dispose();

And don't be shy to use richtextbox for richtext processing. Microsoft itself is doing this here in this tutorial. :-)

Upvotes: 1

mattlant
mattlant

Reputation: 15451

You could create some utility extension methods to make it more 'elegant' :)

public static RichTextBox Set(this RichTextBox rtb, Font font, string text)
{               
    rtb.Text = text;
    rtb.SelectAll();
    rtb.SelectionFont = font;
    rtb.SelectionIndent = 12;
    return rtb;
}

And call like this:

someRtb.Set(yourFont, "The Text").AndThenYouCanAddMoreAndCHainThem();

Edit: I see now that you are not even displaying it. Hrm, interesting, sorry i wasnt of much help with providing a Non Rtb way.

Upvotes: 2

jjxtra
jjxtra

Reputation: 21140

I know it's been a while, but check out this stackoverflow post on converting rtf to html. It would probably be way easier to get your stuff into html, manipulate it, then either display it using html or convert it back to rtf.

Convert Rtf to HTML

Upvotes: 0

jjxtra
jjxtra

Reputation: 21140

Is this project helpful?

http://www.codeproject.com/KB/string/nrtftree.aspx

Upvotes: 3

jwalkerjr
jwalkerjr

Reputation: 1809

I think your technique is a great way to accomplish what you're looking to do. I know what you mean...it feels kind of "dirty" because you're using a Winforms control for something other than it was intended for, but it just works. I've used this technique for years. Interested to see if anyone else has viable options.

Upvotes: 3

hova
hova

Reputation: 2841

You may want to suspend the layout of the richtextbox before you do all of that, to avoid unecessary flicker. That's one of the common mistakes I used to make which made it seem "inelegant"

Upvotes: 3

Related Questions