Ron,
How do I make a rich-text-box save like a normal text file?
-- Alex
Hello Alex,
The RichTextBox control, shown in Figure 1, provides the full power of a relatively sophisticated word processor in a relatively simple ActiveX control that requires surprisingly little coding. At the same time, the control in many respects is an enhanced version of the intrinsic TextBox control, with which it remains compatible.
In other words, the control is designed to seamlessly handle plain ASCII text as well as rich (i.e., formatted) text. Most problems in using the control arise when the programmer expects to be working with text in one format, but instead ends up with text in the other. Imagine, for instance, that you're using automation to retrieve a string of bold text from a Word document to display in the control. The statement
RichTextBox1.Text = _
Word.Application.Selection
assigns the text to the control, but removes all formatting; you end up with plain ASCII text. Instead, to preserve formatting, you want to use the rich text version of the Text property:
RichTextBox1.TextRTF = _
Word.Application.Selection
In this case, no formatting is lost when the formatted Word string is assigned to the control. So in general, the control has two versions of every major property: one that supports rich text, and the other that supports only plain text.
Saving a file works very similarly. The RichTextBox control has a single SaveFile method, but its second parameter indicates the type of file to be saved. Its complete syntax is:
RichTextBox.SaveFile filename, filetype
where filename is the path and filename of the file to be saved, and filetype is a constant or numeric value representing either of the two file types that the control supports: rtfRTF or 0 for rich text, and rtfText or 1 for plain text. If the contents of the control contain rich text, the statement
RichTextBox1.SaveFile _
"MyUnformattedFile.txt", rtfText
removes all formatting.
If you're interested in the details of working with the control, I've found the section on the RichTextBox control in VB Controls in a Nutshell to be particularly good.
I hope that this helps. Good luck with using what is, in my opinion, the most underappreciated and underutilized control included with Visual Basic.
--Ron
Return to: Ron's Archive
Copyright © 2009 O'Reilly Media, Inc.