- Code for the fun of it
RichText Control in C# and VS2005
none Rtf Visual Studio 

Download Demo (67K)
Download source (77K)

RichText Control

The Windows RichTextBox control is a very versatile control that is widely used in Windows Forms applications but the full power of the control is lost without an interface to expose the underlying functionality. To unleash the power of the RichTextBox control a basic understanding of the underlying Rich Text Format (RTF) is helpful but not necessary. There are a host of methods available to the developer that allow for most of the basic functionality to be exploited easily. In order to get a better understanding of what is going on as we progress a brief introduction to the Rich Text Format is in order.

The version of the RichTextBox control that ships with XP is version 3.0 and can be found in the System32 directory with the name "RichEdxx.dll" where xx is the version that you have. While this version has quite an extensive list of features .NET only uses version 2.0 so a lot of these features cannot be accessed using the standard C# RichTextBox control. But fortunatly there is a was around this, by overriding the CreateParams property in our derived class we can essentually get a free upgrade to the latest version of the control.

[DllImport("kernel32.dll", CharSet=CharSet.Auto)]
static extern IntPtr LoadLibrary(string lpFileName);
protected override CreateParams CreateParams
{
get
{
CreateParams prams = base.CreateParams;
if (LoadLibrary("msftedit.dll") != IntPtr.Zero)
{
//The following line may be omitted if you do not wish
// to create the control with a transparent background.
prams.ExStyle |= 0x020;
prams.ClassName = "RICHEDIT50W";]
}
return prams;
}
}

For a full list of versions and what is supported in each version check out Murray Sargents article "Math in Office". As of this writing version 1.9.1 is the current version that is used by Word 2007 and the specification may be donwloaded at: Microsoft download center

Fortunatley we won't have to get our hands dirty learning this very complicated and sometimes frustrating syntax as .NET provides us with some simple methods to deal with most of what we need to do. I won't list or give examples of all these methods but will instead list a few and show how to use them.

In our application we want to be able to do two things; generate the format and be able to detect the chages in the area that it was made. Lets start with an example to change the font style to bold and then detect it as we move around our document. This example uses a ToolStripButton and handles the Click event to set the style by ORing it with the current font style. Then in the SelectioinChanged handler we extract the Font from the current selection and set the ToolStripButton accordingly.

      if (tsbBold.Checked)
wRichTextBox1.SelectionFont = new Font(wRichTextBox1.SelectionFont,
wRichTextBox1.SelectionFont.Style | FontStyle.Bold);
else
wRichTextBox1.SelectionFont = new Font(wRichTextBox1.SelectionFont,
wRichTextBox1.SelectionFont.Style & ~FontStyle.Bold);

private void wRichTextBox1_SelectionChanged(object sender, EventArgs e)
{
Font fnt;

//Get the current selectioins font
if (wRichTextBox1.SelectionFont == null)
return;

fnt = wRichTextBox1.SelectionFont;

//Font Styles
tsbBold.Checked = fnt.Bold;
}

This example shows the way in which we can increase or reduce the indent of our text. The isPlus parameter signifies if we are increasing (isPlus = true) or decreasing the indent. I do not set the ToolStripButton checked property for indenting.

      private void SetIndent(bool isPlus)
{
if (isPlus)
wRichTextBox1.SelectionIndent += _indent;
else
{
if (wRichTextBox1.SelectionIndent >= _indent)
wRichTextBox1.SelectionIndent -= _indent;
else
wRichTextBox1.SelectionIndent = 0;
}
}

If you look in the members section of the RichTextBox control you will find a host of other formats that can be applied to the control. Some other things that can be done are loading and saving of files in either raw text or Rtf formats.

Inserting images at first glance might seem to be a pain but there is a trick that makes it very easy. You can copy your image onto the Clipboard then paste it at the current location in your docment. The next example shows how to do this.

      private void InsertPicture()
{
openFileDialog1.Filter =
"Image Files(*.BMP;*.JPG;*.GIF;*.PNG;*.ICO)|*.BMP;*.JPG;*.GIF;*.PNG;
*.ICO|All files (*.*)|*.*";
DialogResult dr = openFileDialog1.ShowDialog();
if (dr == DialogResult.OK)
{
try
{
string file = openFileDialog1.FileName;

PasteImage(file);
}
catch (Exception x)
{
MessageBox.Show("Problem encountered during paste: " + x.Message);
}
}
}

private void PasteImage(string file)
{
try
{
Image img = Bitmap.FromFile(file);
Clipboard.SetImage(img);
wRichTextBox1.Paste();
}
catch
{
MessageBox.Show(this,
"Most likely an invalid image",
"Invalid Image",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}

There is much more that can be done using this control but I thought a basic control, that was lightweight and easy to use would be of most benefit as there don't seem to be to many of them out there that are free. Enjoy!

back to top
Comment on this article
Longnn Says
6/4/2010 5:48:30 AM

I want to ask how to modify look and feel of a control.Example , i want to modify scroll bar of richtextbox control by my own images. Contact me if you want to help.THanks so much
Mike Says
6/8/2010 2:20:49 PM

longnn, It's been a long time since I've done anything with this control but as I remember you will have to make calls to the Windows API to be able to control the look and feel of the control. To do this you will either have to write your code in C++ or if using C# use Platform Invoke service calls, PInvoke. Check out this site http://www.pinvoke.net/ You should give you what you need to do what you want. Good luck, Mike
Name
Email