WWW Yariv Hammer's Code Site

Monday, October 24, 2005

Making RichTextBox Readonly (With Rtf)

I recently needed to place an RTF file with pictures in side a RichTextBox. This is a very easy procedure: Simply call the LoadFile method of RichTextBox. The advantages of using RTF is the ability to create a very complex document using Microsoft word, and displaying it on my form. The user can edit the contents of the control and save it in a rich text format. In my case I used it because I needed to show the user lots of pictures in one control, and he could scroll up and down to see all of them.

The Problem
I needed to prevent the user from editing the contents of the RichTextBox.
I tried the Enabled property. Setting it to false disabled the Scroll Bar of the RichTextBox. Without it the user can't see all the pictures, so this is out of the question.
I tried the ReadOnly property. It does nothing when loading RTF files.
I needed to find some other way to prevent the user from editing. I had a really serious problem, because when the RTF contains pictures, those can be selected by the user and deleted by pressing on the delete key.

The Solution
The best solution I could come up with is disabling the click event, the MouseDown KeyDown and Enter event. Some of them require another control to receive focus:

private void richTextBox1_MouseDown(object sender, MouseEventArgs e)
   textBox1.Focus(); //To remove the focus to another control.
private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
   e.Handled = true;
private void richTextBox1_Enter(object sender, EventArgs e)
   textBox1.Focus(); //To remove the focus to another control.


Feel free to use everything here. Add links to my site if you wish.

Do not copy anything to other sites without adding link to here.

All the contents of the site belong to Yariv Hammer.