Click here to Skip to main content
15,892,697 members
Articles / Programming Languages / C#
Article

RicherTextBox

Rate me:
Please Sign up or sign in to vote.
4.82/5 (19 votes)
17 Mar 2008CPOL3 min read 138.1K   14K   90   29
User control for .NET 2.0 extending RichTextBox with various formatting options
Image 1

Introduction

The RicherTextBox .NET user control is an extension of the RichTextBox control. It has integrated toolstrips with the most common formatting options - choosing fonts, font style (bold, underline, italic), text alignment, bullets, indentation, zooming in and out and searching and replacing. Each one of the tools in the toolstrip can be hidden or shown in design-time or by using the code. In addition to the toolstrip, most of the functionality is also combined in a context menu. It also contains public methods for managing the format using code when the usage of the toolstrip is not appropriate. Save and load funcionality is also implemented. The RicherTextBox control is ready-to-use and its basic usage is as easy as dragging it from the toolbox into the container.

The toolstrip of RicherTextBox:

Sample Image - maximum width is 600 pixels

The context menu of RicherTextBox:

Sample Image - maximum width is 600 pixels

Using the Code

This control should be used as any other user control - just drag-drop in a designer, or create a new instance using a code editor. The only thing you need to do is to add a reference to the DLL-file of the control or the whole project in your project's references and add a using directive in your code file to the namespace RicherTextBox.

C#
// Include RicherTextBox namespace to be able to access the control's 
// properties and methods
using RicherTextBox;

Without any other code, the control will became available in its full capabilities. If you want to enable or disable some functionality, it can be done in design time using the properties in Toolstrip items visibility and Toolstrip single items visibility categories, or by setting them using C# code.

Here are some examples of hiding items in the toolstrip using code. Let's assume that the control is implemented in a form and its name is set to richerTextBox1 .

Hiding a group of tools:

C#
//
// To hide the group of buttons for text alignment using the properties
//
richerTextBox1.GroupAlignmentVisible = false;
//
// To hide the group of buttons for text alignment using the methods
//
richerTextBox1.HideToolstripItemsByGroup
    (RicherTextBox.RicherTextBoxToolStripGroups.Alignment, false);

The method HideToolstripItemsByGroup is declared as follows...

C#
public void HideToolstripItemsByGroup
   (RicherTextBoxToolStripGroups group, bool visible)

... where RicherTextBoxToolStripGroups is enumeration including the values:

C#
public enum RicherTextBoxToolStripGroups
{
    SaveAndLoad = 0x1,
    FontNameAndSize = 0x2,
    BoldUnderlineItalic = 0x4,
    Alignment = 0x8,
    FontColor = 0x10,
    IndentationAndBullets = 0x20,
    Insert = 0x40,
    Zoom = 0x80
}

The values in HideToolstripItemsByGroup's first parameter can be combined using the bitwise or operator (|):

C#
// Hiding more than one group of tools using a combination of enumerable values 
// as a parameter
richerTextBox1.HideToolstripItemsByGroup(
    RicherTextBoxToolStripGroups.Alignment |
    RicherTextBoxToolStripGroups.BoldUnderlineItalic,
    false);

This is what the control looks like after executing this code:

Sample Image - maximum width is 600 pixels

As you can see, the alignment buttons and the bold, italic, underline buttons are now hidden.

Using the Methods for Accessing Functionality (Examples)

Let's say you want to toggle the bold parameter of the selected text from the code, it is done in a very simple way:

C#
// Toggling Bold on the selected text
richerTextBox1.ToggleBold();    

Setting the size of the used font:

C#
// Setting the font size
richerTextBox1.SetFontSize(8.25f);

The same is used for all of the formatting functionality of the control.

If you don't want the save and load buttons visible (or, even if they're visible), you will probably want to access the text which the user has typed in the control. Two properties are supplied for this purpose:

  • Text is an overriding property which contains the text in the RicherTextBox in plain-text format.
  • Rtf holds the text in rich-text format.

Both properties can be set and read, and the Rtf property also has simple error protection: when a string with invalid format is associated with it, instead of throwing ArgumentException, the invalid text is simply set as plain-text format:

C#
// Setting the text
richTextBox1.Text = "This is an example of setting the text in a RicherTextBox";

// Now, an example of setting the Rtf property to an invalid value:
// The value "Test" is an invalid rich-text format string, but the RicherTextBox
// control will simply read it as plain-text instead of throwing exceptions
richTextBox1.Rtf = "Test";    

Searching and Replacing

All that you need is to show (or, not hide) the toolstrip for finding. All functionality of searching and replacing is integrated in the control.

Sample Image - maximum width is 600 pixels

History

  • Version 1.0 - 16 March, 2008: First released version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Interconsult Bulgaria
Bulgaria Bulgaria
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
ABJ Bahadır Back12-Nov-21 6:40
ABJ Bahadır Back12-Nov-21 6:40 
GeneralMy vote of 5 Pin
Member 381004229-Nov-19 9:24
Member 381004229-Nov-19 9:24 
QuestionOpening a string - fails Pin
Member 1298335819-Apr-17 23:00
Member 1298335819-Apr-17 23:00 
Questionabraham Pin
Abraham Molina12-Oct-16 9:34
Abraham Molina12-Oct-16 9:34 
QuestionNeed additional properties Pin
Srikanth Anandateertha18-Oct-13 8:42
Srikanth Anandateertha18-Oct-13 8:42 
QuestionTextChanged Pin
AdrianoG30-Jul-13 3:27
AdrianoG30-Jul-13 3:27 
AnswerRe: TextChanged Pin
Simon Jeffs10-Jun-20 2:34
Simon Jeffs10-Jun-20 2:34 
QuestionUse on Multiple RichTextBoxes? Pin
trantrum27-May-13 2:13
professionaltrantrum27-May-13 2:13 
QuestionRead-Only Text Pin
Elie Mouawad7-Jan-13 3:37
Elie Mouawad7-Jan-13 3:37 
AnswerRe: Read-Only Text Pin
trantrum27-May-13 1:35
professionaltrantrum27-May-13 1:35 
QuestionHow to get the selected text Pin
The_F1-May-12 23:58
The_F1-May-12 23:58 
QuestionProblem with adding multiple instance of RicherTextBox to a form Pin
FernandoUY6-Mar-12 4:46
professionalFernandoUY6-Mar-12 4:46 
AnswerRe: Problem with adding multiple instance of RicherTextBox to a form Pin
FernandoUY6-Mar-12 4:53
professionalFernandoUY6-Mar-12 4:53 
Questionhow to give html input? Pin
Joyalg16-Feb-10 2:21
Joyalg16-Feb-10 2:21 
GeneralI added a ValueChanged event to the control... Pin
Steve McKenna1-Feb-10 6:42
Steve McKenna1-Feb-10 6:42 
Svetoslav,
Thank you so much for creating this control, it was awesome!
However, I found it was missing one key feature that I really needed: an event the fires whenever the user changes anything in the control. Therefore, I added a ValueChanged event to your code. Please consider accepting the updated version of the code below (changes are at or near the bottom)....

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace RicherTextBox
{
public enum RicherTextBoxToolStripGroups
{
SaveAndLoad = 0x1,
FontNameAndSize = 0x2,
BoldUnderlineItalic = 0x4,
Alignment = 0x8,
FontColor = 0x10,
IndentationAndBullets = 0x20,
Insert = 0x40,
Zoom = 0x80
}

public partial class RicherTextBox : UserControl
{
#region Settings
private int indent = 10;
[Category("Settings")]
[Description("Value indicating the number of characters used for indentation")]
public int INDENT
{
get { return indent; }
set { indent = value; }
}
#endregion

#region Properties for toolstrip items visibility
[Category("Toolstip items visibility")]
public bool GroupSaveAndLoadVisible
{
get { return IsGroupVisible(RicherTextBoxToolStripGroups.SaveAndLoad); }
set { HideToolstripItemsByGroup(RicherTextBoxToolStripGroups.SaveAndLoad, value); }
}
[Category("Toolstip items visibility")]
public bool GroupFontNameAndSizeVisible
{
get { return IsGroupVisible(RicherTextBoxToolStripGroups.FontNameAndSize); }
set { HideToolstripItemsByGroup(RicherTextBoxToolStripGroups.FontNameAndSize, value); }
}
[Category("Toolstip items visibility")]
public bool GroupBoldUnderlineItalicVisible
{
get { return IsGroupVisible(RicherTextBoxToolStripGroups.BoldUnderlineItalic); }
set { HideToolstripItemsByGroup(RicherTextBoxToolStripGroups.BoldUnderlineItalic, value); }
}
[Category("Toolstip items visibility")]
public bool GroupAlignmentVisible
{
get { return IsGroupVisible(RicherTextBoxToolStripGroups.Alignment); }
set { HideToolstripItemsByGroup(RicherTextBoxToolStripGroups.Alignment, value); }
}
[Category("Toolstip items visibility")]
public bool GroupFontColorVisible
{
get { return IsGroupVisible(RicherTextBoxToolStripGroups.FontColor); }
set { HideToolstripItemsByGroup(RicherTextBoxToolStripGroups.FontColor, value); }
}
[Category("Toolstip items visibility")]
public bool GroupIndentationAndBulletsVisible
{
get { return IsGroupVisible(RicherTextBoxToolStripGroups.IndentationAndBullets); }
set { HideToolstripItemsByGroup(RicherTextBoxToolStripGroups.IndentationAndBullets, value); }
}
[Category("Toolstip items visibility")]
public bool GroupInsertVisible
{
get { return IsGroupVisible(RicherTextBoxToolStripGroups.Insert); }
set { HideToolstripItemsByGroup(RicherTextBoxToolStripGroups.Insert, value); }
}
[Category("Toolstip items visibility")]
public bool GroupZoomVisible
{
get { return IsGroupVisible(RicherTextBoxToolStripGroups.Zoom); }
set { HideToolstripItemsByGroup(RicherTextBoxToolStripGroups.Zoom, value); }
}
[Category("Toolstip items visibility")]
public bool ToolStripVisible
{
get { return toolStrip1.Visible; }
set { toolStrip1.Visible = value; }
}
[Category("Toolstip items visibility")]
public bool FindReplaceVisible
{
get { return toolStripFindReplace.Visible; }
set { toolStripFindReplace.Visible = value; }
}

[Category("Toolstrip single items visibility")]
public bool SaveVisible
{
get { return tsbtnSave.Visible; }
set { tsbtnSave.Visible = value; }
}
[Category("Toolstrip single items visibility")]
public bool LoadVisible
{
get { return tsbtnOpen.Visible; }
set { tsbtnOpen.Visible = value; }
}
[Category("Toolstrip single items visibility")]
public bool SeparatorSaveLoadVisible
{
get { return toolStripSeparator6.Visible; }
set { toolStripSeparator6.Visible = value; }
}
[Category("Toolstrip single items visibility")]
public bool FontFamilyVisible
{
get { return tscmbFont.Visible; }
set { tscmbFont.Visible = value; }
}
[Category("Toolstrip single items visibility")]
public bool FontSizeVisible
{
get { return tscmbFontSize.Visible; }
set { tscmbFontSize.Visible = value; }
}
[Category("Toolstrip single items visibility")]
public bool ChooseFontVisible
{
get { return tsbtnChooseFont.Visible; }
set { tsbtnChooseFont.Visible = value; }
}
[Category("Toolstrip single items visibility")]
public bool SeparatorFontVisible
{
get { return toolStripSeparator1.Visible; }
set { toolStripSeparator1.Visible = value; }
}
[Category("Toolstrip single items visibility")]
public bool BoldVisible
{
get { return tsbtnBold.Visible; }
set { tsbtnBold.Visible = value; }
}
[Category("Toolstrip single items visibility")]
public bool ItalicVisible
{
get { return tsbtnItalic.Visible; }
set { tsbtnItalic.Visible = value; }
}
[Category("Toolstrip single items visibility")]
public bool UnderlineVisible
{
get { return tsbtnUnderline.Visible; }
set { tsbtnUnderline.Visible = value; }
}
[Category("Toolstrip single items visibility")]
public bool SeparatorBoldUnderlineItalicVisible
{
get { return toolStripSeparator2.Visible; }
set { toolStripSeparator2.Visible = value; }
}
[Category("Toolstrip single items visibility")]
public bool AlignLeftVisible
{
get { return tsbtnAlignLeft.Visible; }
set { tsbtnAlignLeft.Visible = value; }
}
[Category("Toolstrip single items visibility")]
public bool AlignRightVisible
{
get { return tsbtnAlignRight.Visible; }
set { tsbtnAlignRight.Visible = value; }
}
[Category("Toolstrip single items visibility")]
public bool AlignCenterVisible
{
get { return tsbtnAlignCenter.Visible; }
set { tsbtnAlignCenter.Visible = value; }
}
[Category("Toolstrip single items visibility")]
public bool SeparatorAlignVisible
{
get { return toolStripSeparator3.Visible; }
set { toolStripSeparator3.Visible = value; }
}
[Category("Toolstrip single items visibility")]
public bool FontColorVisible
{
get { return tsbtnFontColor.Visible; }
set { tsbtnFontColor.Visible = value; }
}
[Category("Toolstrip single items visibility")]
public bool WordWrapVisible
{
get { return tsbtnWordWrap.Visible; }
set { tsbtnWordWrap.Visible = value; }
}
[Category("Toolstrip single items visibility")]
public bool SeparatorFontColorVisible
{
get { return toolStripSeparator4.Visible; }
set { toolStripSeparator4.Visible = value; }
}
[Category("Toolstrip single items visibility")]
public bool IndentVisible
{
get { return tsbtnIndent.Visible; }
set { tsbtnIndent.Visible = value; }
}
[Category("Toolstrip single items visibility")]
public bool OutdentVisible
{
get { return tsbtnOutdent.Visible; }
set { tsbtnOutdent.Visible = value; }
}
[Category("Toolstrip single items visibility")]
public bool BulletsVisible
{
get { return tsbtnBullets.Visible; }
set { tsbtnBullets.Visible = value; }
}
[Category("Toolstrip single items visibility")]
public bool SeparatorIndentAndBulletsVisible
{
get { return toolStripSeparator5.Visible; }
set { toolStripSeparator5.Visible = value; }
}
[Category("Toolstrip single items visibility")]
public bool InsertPictureVisible
{
get { return tsbtnInsertPicture.Visible; }
set { tsbtnInsertPicture.Visible = value; }
}
[Category("Toolstrip single items visibility")]
public bool SeparatorInsertVisible
{
get { return toolStripSeparator7.Visible; }
set { toolStripSeparator7.Visible = value; }
}
[Category("Toolstrip single items visibility")]
public bool ZoomInVisible
{
get { return tsbtnZoomIn.Visible; }
set { tsbtnZoomIn.Visible = value; }
}
[Category("Toolstrip single items visibility")]
public bool ZoomOutVisible
{
get { return tsbtnZoomOut.Visible; }
set { tsbtnZoomOut.Visible = value; }
}
[Category("Toolstrip single items visibility")]
public bool ZoomFactorTextVisible
{
get { return tstxtZoomFactor.Visible; }
set { tstxtZoomFactor.Visible = value; }
}

#endregion

#region data properties
[Category("Document data")]
[Description("RicherTextBox content in plain text")]
[Browsable(true)]
public override string Text
{
get { return rtbDocument.Text; }
set { rtbDocument.Text = value; }
}
[Category("Document data")]
[Description("RicherTextBox content in rich-text format")]
public string Rtf
{
get { return rtbDocument.Rtf; }
set { try { rtbDocument.Rtf = value; } catch (ArgumentException) { rtbDocument.Text = value; } }
}

#endregion


#region Construction and initial loading
public RicherTextBox()
{
InitializeComponent();
}

private void RicherTextBox_Load(object sender, EventArgs e)
{
// load system fonts
foreach (FontFamily family in FontFamily.Families)
{
tscmbFont.Items.Add(family.Name);
}
tscmbFont.SelectedItem = "Microsoft Sans Serif";

tscmbFontSize.SelectedItem = "9";

tstxtZoomFactor.Text = Convert.ToString(rtbDocument.ZoomFactor * 100);
tsbtnWordWrap.Checked = rtbDocument.WordWrap;
}

#endregion

#region Toolstrip items handling

private void tsbtnBIU_Click(object sender, EventArgs e)
{
// bold, italic, underline
try
{
if (!(rtbDocument.SelectionFont == null))
{
Font currentFont = rtbDocument.SelectionFont;
FontStyle newFontStyle = rtbDocument.SelectionFont.Style;
string txt = (sender as ToolStripButton).Name;
if (txt.IndexOf("Bold") >= 0)
newFontStyle = rtbDocument.SelectionFont.Style ^ FontStyle.Bold;
else if (txt.IndexOf("Italic") >= 0)
newFontStyle = rtbDocument.SelectionFont.Style ^ FontStyle.Italic;
else if (txt.IndexOf("Underline") >= 0)
newFontStyle = rtbDocument.SelectionFont.Style ^ FontStyle.Underline;

rtbDocument.SelectionFont = new Font(currentFont.FontFamily, currentFont.Size, newFontStyle);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString(), "Error");
}
}

private void rtbDocument_SelectionChanged(object sender, EventArgs e)
{
if (rtbDocument.SelectionFont != null)
{
tsbtnBold.Checked = rtbDocument.SelectionFont.Bold;
tsbtnItalic.Checked = rtbDocument.SelectionFont.Italic;
tsbtnUnderline.Checked = rtbDocument.SelectionFont.Underline;

boldToolStripMenuItem.Checked = rtbDocument.SelectionFont.Bold;
italicToolStripMenuItem.Checked = rtbDocument.SelectionFont.Italic;
underlineToolStripMenuItem.Checked = rtbDocument.SelectionFont.Underline;

switch (rtbDocument.SelectionAlignment)
{
case HorizontalAlignment.Left:
tsbtnAlignLeft.Checked = true;
tsbtnAlignCenter.Checked = false;
tsbtnAlignRight.Checked = false;

leftToolStripMenuItem.Checked = true;
centerToolStripMenuItem.Checked = false;
rightToolStripMenuItem.Checked = false;
break;

case HorizontalAlignment.Center:
tsbtnAlignLeft.Checked = false;
tsbtnAlignCenter.Checked = true;
tsbtnAlignRight.Checked = false;

leftToolStripMenuItem.Checked = false;
centerToolStripMenuItem.Checked = true;
rightToolStripMenuItem.Checked = false;
break;

case HorizontalAlignment.Right:
tsbtnAlignLeft.Checked = false;
tsbtnAlignCenter.Checked = false;
tsbtnAlignRight.Checked = true;

leftToolStripMenuItem.Checked = false;
centerToolStripMenuItem.Checked = false;
rightToolStripMenuItem.Checked = true;
break;
}

tsbtnBullets.Checked = rtbDocument.SelectionBullet;
bulletsToolStripMenuItem.Checked = rtbDocument.SelectionBullet;

tscmbFont.SelectedItem = rtbDocument.SelectionFont.FontFamily.Name;
tscmbFontSize.SelectedItem = rtbDocument.SelectionFont.Size.ToString();
}
}

private void tsbtnAlignment_Click(object sender, EventArgs e)
{
// alignment: left, center, right
try
{
string txt = (sender as ToolStripButton).Name;
if (txt.IndexOf("Left") >= 0)
{
rtbDocument.SelectionAlignment = HorizontalAlignment.Left;
tsbtnAlignLeft.Checked = true;
tsbtnAlignCenter.Checked = false;
tsbtnAlignRight.Checked = false;
}
else if (txt.IndexOf("Center") >= 0)
{
rtbDocument.SelectionAlignment = HorizontalAlignment.Center;
tsbtnAlignLeft.Checked = false;
tsbtnAlignCenter.Checked = true;
tsbtnAlignRight.Checked = false;
}
else if (txt.IndexOf("Right") >= 0)
{
rtbDocument.SelectionAlignment = HorizontalAlignment.Right;
tsbtnAlignLeft.Checked = false;
tsbtnAlignCenter.Checked = false;
tsbtnAlignRight.Checked = true;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString(), "Error");
}
}

private void tsbtnFontColor_Click(object sender, EventArgs e)
{
// font color
try
{
using (ColorDialog dlg = new ColorDialog())
{
dlg.Color = rtbDocument.SelectionColor;
if (dlg.ShowDialog() == DialogResult.OK)
{
rtbDocument.SelectionColor = dlg.Color;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString(), "Error");
}
}

private void tsbtnBulletsAndNumbering_Click(object sender, EventArgs e)
{
// bullets, indentation
try
{
string name = (sender as ToolStripButton).Name;
if (name.IndexOf("Bullets") >= 0)
rtbDocument.SelectionBullet = tsbtnBullets.Checked;
else if (name.IndexOf("Indent") >= 0)
rtbDocument.SelectionIndent += INDENT;
else if (name.IndexOf("Outdent") >= 0)
rtbDocument.SelectionIndent -= INDENT;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString(), "Error");
}
}

private void tscmbFontSize_Click(object sender, EventArgs e)
{
// font size
try
{
if (!(rtbDocument.SelectionFont == null))
{
Font currentFont = rtbDocument.SelectionFont;
float newSize = Convert.ToSingle(tscmbFontSize.SelectedItem.ToString());
rtbDocument.SelectionFont = new Font(currentFont.FontFamily, newSize, currentFont.Style);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString(), "Error");
}
}


private void tscmbFontSize_TextChanged(object sender, EventArgs e)
{
// font size custom
try
{
if (!(rtbDocument.SelectionFont == null))
{
Font currentFont = rtbDocument.SelectionFont;
float newSize = Convert.ToSingle(tscmbFontSize.Text);
rtbDocument.SelectionFont = new Font(currentFont.FontFamily, newSize, currentFont.Style);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString(), "Error");
}
}

private void tscmbFont_Click(object sender, EventArgs e)
{
// font
try
{
if (!(rtbDocument.SelectionFont == null))
{
Font currentFont = rtbDocument.SelectionFont;
FontFamily newFamily = new FontFamily(tscmbFont.SelectedItem.ToString());
rtbDocument.SelectionFont = new Font(newFamily, currentFont.Size, currentFont.Style);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString(), "Error");
}
}

private void btnChooseFont_Click(object sender, EventArgs e)
{
using (FontDialog dlg = new FontDialog())
{
if (rtbDocument.SelectionFont != null) dlg.Font = rtbDocument.SelectionFont;
if (dlg.ShowDialog() == DialogResult.OK)
{
rtbDocument.SelectionFont = dlg.Font;
}
}
}

private void tsbtnInsertPicture_Click(object sender, EventArgs e)
{
using (OpenFileDialog dlg = new OpenFileDialog())
{
dlg.Title = "Insert picture";
dlg.DefaultExt = "jpg";
dlg.Filter = "Bitmap Files|*.bmp|JPEG Files|*.jpg|GIF Files|*.gif|All files|*.*";
dlg.FilterIndex = 1;
if (dlg.ShowDialog() == DialogResult.OK)
{
try
{
string strImagePath = dlg.FileName;
Image img = Image.FromFile(strImagePath);
Clipboard.SetDataObject(img);
DataFormats.Format df;
df = DataFormats.GetFormat(DataFormats.Bitmap);
if (this.rtbDocument.CanPaste(df))
{
this.rtbDocument.Paste(df);
}
}
catch
{
MessageBox.Show("Unable to insert image.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

private void tsbtnSave_Click(object sender, EventArgs e)
{
using (SaveFileDialog dlg = new SaveFileDialog())
{
dlg.Filter = "Rich text format|*.rtf";
dlg.FilterIndex = 0;
dlg.OverwritePrompt = true;
if (dlg.ShowDialog() == DialogResult.OK)
{
try
{
rtbDocument.SaveFile(dlg.FileName, RichTextBoxStreamType.RichText);
}
catch (IOException exc)
{
MessageBox.Show("Error writing file: \n" + exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (ArgumentException exc_a)
{
MessageBox.Show("Error writing file: \n" + exc_a.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

private void tsbtnOpen_Click(object sender, EventArgs e)
{
using (OpenFileDialog dlg = new OpenFileDialog())
{
dlg.Filter = "Rich text format|*.rtf";
dlg.FilterIndex = 0;
if (dlg.ShowDialog() == DialogResult.OK)
{
try
{
rtbDocument.LoadFile(dlg.FileName, RichTextBoxStreamType.RichText);
}
catch (IOException exc)
{
MessageBox.Show("Error reading file: \n" + exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (ArgumentException exc_a)
{
MessageBox.Show("Error reading file: \n" + exc_a.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

}
}
}

private void toolStripButton1_Click(object sender, EventArgs e)
{
if (rtbDocument.ZoomFactor < 64.0f - 0.20f)
{
rtbDocument.ZoomFactor += 0.20f;
tstxtZoomFactor.Text = String.Format("{0:F0}", rtbDocument.ZoomFactor * 100);
}
}

private void tsbtnZoomOut_Click(object sender, EventArgs e)
{
if (rtbDocument.ZoomFactor > 0.16f + 0.20f)
{
rtbDocument.ZoomFactor -= 0.20f;
tstxtZoomFactor.Text = String.Format("{0:F0}", rtbDocument.ZoomFactor * 100);
}
}

private void tstxtZoomFactor_Leave(object sender, EventArgs e)
{
try
{
rtbDocument.ZoomFactor = Convert.ToSingle(tstxtZoomFactor.Text) / 100;
}
catch (FormatException)
{
MessageBox.Show("Enter valid number", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
tstxtZoomFactor.Focus();
tstxtZoomFactor.SelectAll();
}
catch (OverflowException)
{
MessageBox.Show("Enter valid number", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
tstxtZoomFactor.Focus();
tstxtZoomFactor.SelectAll();
}
catch (ArgumentException)
{
MessageBox.Show("Zoom factor should be between 20% and 6400%", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
tstxtZoomFactor.Focus();
tstxtZoomFactor.SelectAll();
}
}


private void tsbtnWordWrap_Click(object sender, EventArgs e)
{
rtbDocument.WordWrap = tsbtnWordWrap.Checked;
}

#endregion

#region Changing visibility of toolstrip items

public void HideToolstripItemsByGroup(RicherTextBoxToolStripGroups group, bool visible)
{
if ((group & RicherTextBoxToolStripGroups.SaveAndLoad) != 0)
{
tsbtnSave.Visible = visible;
tsbtnOpen.Visible = visible;
toolStripSeparator6.Visible = visible;
}
if ((group & RicherTextBoxToolStripGroups.FontNameAndSize) != 0)
{
tscmbFont.Visible = visible;
tscmbFontSize.Visible = visible;
tsbtnChooseFont.Visible = visible;
toolStripSeparator1.Visible = visible;
}
if ((group & RicherTextBoxToolStripGroups.BoldUnderlineItalic) != 0)
{
tsbtnBold.Visible = visible;
tsbtnItalic.Visible = visible;
tsbtnUnderline.Visible = visible;
toolStripSeparator2.Visible = visible;
}
if ((group & RicherTextBoxToolStripGroups.Alignment) != 0)
{
tsbtnAlignLeft.Visible = visible;
tsbtnAlignRight.Visible = visible;
tsbtnAlignCenter.Visible = visible;
toolStripSeparator3.Visible = visible;
}
if ((group & RicherTextBoxToolStripGroups.FontColor) != 0)
{
tsbtnFontColor.Visible = visible;
tsbtnWordWrap.Visible = visible;
toolStripSeparator4.Visible = visible;
}
if ((group & RicherTextBoxToolStripGroups.IndentationAndBullets) != 0)
{
tsbtnIndent.Visible = visible;
tsbtnOutdent.Visible = visible;
tsbtnBullets.Visible = visible;
toolStripSeparator5.Visible = visible;
}
if ((group & RicherTextBoxToolStripGroups.Insert) != 0)
{
tsbtnInsertPicture.Visible = visible;
toolStripSeparator7.Visible = visible;
}
if ((group & RicherTextBoxToolStripGroups.Zoom) != 0)
{
tsbtnZoomOut.Visible = visible;
tsbtnZoomIn.Visible = visible;
tstxtZoomFactor.Visible = visible;
}
}

public bool IsGroupVisible(RicherTextBoxToolStripGroups group)
{
switch (group)
{
case RicherTextBoxToolStripGroups.SaveAndLoad:
return tsbtnSave.Visible && tsbtnOpen.Visible && toolStripSeparator6.Visible;

case RicherTextBoxToolStripGroups.FontNameAndSize:
return tscmbFont.Visible && tscmbFontSize.Visible && tsbtnChooseFont.Visible && toolStripSeparator1.Visible;

case RicherTextBoxToolStripGroups.BoldUnderlineItalic:
return tsbtnBold.Visible && tsbtnItalic.Visible && tsbtnUnderline.Visible && toolStripSeparator2.Visible;

case RicherTextBoxToolStripGroups.Alignment:
return tsbtnAlignLeft.Visible && tsbtnAlignRight.Visible && tsbtnAlignCenter.Visible && toolStripSeparator3.Visible;

case RicherTextBoxToolStripGroups.FontColor:
return tsbtnFontColor.Visible && tsbtnWordWrap.Visible && toolStripSeparator4.Visible;

case RicherTextBoxToolStripGroups.IndentationAndBullets:
return tsbtnIndent.Visible && tsbtnOutdent.Visible && tsbtnBullets.Visible && toolStripSeparator5.Visible;

case RicherTextBoxToolStripGroups.Insert:
return tsbtnInsertPicture.Visible && toolStripSeparator7.Visible;

case RicherTextBoxToolStripGroups.Zoom:
return tsbtnZoomOut.Visible && tsbtnZoomIn.Visible && tstxtZoomFactor.Visible;

default:
return false;
}
}
#endregion

#region Public methods for accessing the functionality of the RicherTextBox

public void SetFontFamily(FontFamily family)
{
if (family != null)
{
tscmbFont.SelectedItem = family.Name;
}
}

public void SetFontSize(float newSize)
{
tscmbFontSize.Text = newSize.ToString();
}

public void ToggleBold()
{
tsbtnBold.PerformClick();
}

public void ToggleItalic()
{
tsbtnItalic.PerformClick();
}

public void ToggleUnderline()
{
tsbtnUnderline.PerformClick();
}

public void SetAlign(HorizontalAlignment alignment)
{
switch (alignment)
{
case HorizontalAlignment.Center:
tsbtnAlignCenter.PerformClick();
break;

case HorizontalAlignment.Left:
tsbtnAlignLeft.PerformClick();
break;

case HorizontalAlignment.Right:
tsbtnAlignRight.PerformClick();
break;
}
}

public void Indent()
{
tsbtnIndent.PerformClick();
}

public void Outdent()
{
tsbtnOutdent.PerformClick();
}

public void ToggleBullets()
{
tsbtnBullets.PerformClick();
}

public void ZoomIn()
{
tsbtnZoomIn.PerformClick();
}

public void ZoomOut()
{
tsbtnZoomOut.PerformClick();
}

public void ZoomTo(float factor)
{
rtbDocument.ZoomFactor = factor;
}

public void SetWordWrap(bool activated)
{
rtbDocument.WordWrap = activated;
}
#endregion


#region Context menu handlers
private void cutToolStripMenuItem_Click(object sender, EventArgs e)
{
rtbDocument.Cut();
}

private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
rtbDocument.Copy();
}

private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{
rtbDocument.Paste();
}

private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
{
rtbDocument.Clear();
}

private void selectAllToolStripMenuItem_Click(object sender, EventArgs e)
{
rtbDocument.SelectAll();
}

private void undoToolStripMenuItem_Click(object sender, EventArgs e)
{
rtbDocument.Undo();
}

private void redoToolStripMenuItem_Click(object sender, EventArgs e)
{
rtbDocument.Redo();
}

private void leftToolStripMenuItem_Click(object sender, EventArgs e)
{
tsbtnAlignLeft.PerformClick();

leftToolStripMenuItem.Checked = true;
centerToolStripMenuItem.Checked = false;
rightToolStripMenuItem.Checked = false;


}

private void centerToolStripMenuItem_Click(object sender, EventArgs e)
{
tsbtnAlignCenter.PerformClick();

leftToolStripMenuItem.Checked = false;
centerToolStripMenuItem.Checked = true;
rightToolStripMenuItem.Checked = false;
}

private void rightToolStripMenuItem_Click(object sender, EventArgs e)
{
tsbtnAlignRight.PerformClick();

leftToolStripMenuItem.Checked = false;
centerToolStripMenuItem.Checked = false;
rightToolStripMenuItem.Checked = true;
}

private void boldToolStripMenuItem_Click(object sender, EventArgs e)
{
tsbtnBold.PerformClick();
}

private void italicToolStripMenuItem_Click(object sender, EventArgs e)
{
tsbtnItalic.PerformClick();
}

private void underlineToolStripMenuItem_Click(object sender, EventArgs e)
{
tsbtnUnderline.PerformClick();
}

private void increaseToolStripMenuItem_Click(object sender, EventArgs e)
{
tsbtnIndent.PerformClick();
}

private void decreaseToolStripMenuItem_Click(object sender, EventArgs e)
{
tsbtnOutdent.PerformClick();
}

private void bulletsToolStripMenuItem_Click(object sender, EventArgs e)
{
tsbtnBullets.PerformClick();
}

private void zoomInToolStripMenuItem_Click(object sender, EventArgs e)
{
tsbtnZoomIn.PerformClick();
}

private void zoomOuToolStripMenuItem_Click(object sender, EventArgs e)
{
tsbtnZoomOut.PerformClick();
}

private void insertPictureToolStripMenuItem_Click(object sender, EventArgs e)
{
tsbtnInsertPicture.PerformClick();
}

#endregion

#region Find and Replace
private void tsbtnFind_Click(object sender, EventArgs e)
{
FindForm findForm = new FindForm();
findForm.RtbInstance = this.rtbDocument;
findForm.InitialText = this.tstxtSearchText.Text;
findForm.Show();
}

private void tsbtnReplace_Click(object sender, EventArgs e)
{
ReplaceForm replaceForm = new ReplaceForm();
replaceForm.RtbInstance = this.rtbDocument;
replaceForm.InitialText = this.tstxtSearchText.Text;
replaceForm.Show();
}
#endregion

// Declare an event
public event ValueChangedEventHandler ValueChanged;

protected virtual void OnValueChanged(ValueChangedEventArgs e)
{
if (ValueChanged != null)
ValueChanged(this, e);
}

private void rtbDocument_TextChanged(object sender, EventArgs e)
{
// Raise the event
int value = 0;
OnValueChanged(new ValueChangedEventArgs(value));
}

}

public class ValueChangedEventArgs : EventArgs
{
public int NewValue { get; set; }

public ValueChangedEventArgs(int newValue)
{
NewValue = newValue;
}
}

// Declare a delegate
public delegate void ValueChangedEventHandler(object sender,
ValueChangedEventArgs e);

}
Questionis it possible to open a specific *.rtf file by parameter ? Pin
Bernd Pfeiff6-Dec-09 3:47
Bernd Pfeiff6-Dec-09 3:47 
QuestionHow to numbering a line Pin
laduc1-Dec-09 15:35
laduc1-Dec-09 15:35 
Generalsave RicherTextBox Content to DB Pin
Bernd Pfeiff3-Sep-09 6:39
Bernd Pfeiff3-Sep-09 6:39 
QuestionHtml export Pin
Member 351717930-May-08 5:01
Member 351717930-May-08 5:01 
Generalmultiple font attributes Pin
Gary O'Neal25-Mar-08 4:54
Gary O'Neal25-Mar-08 4:54 
QuestionTables? Pin
georani25-Mar-08 2:48
georani25-Mar-08 2:48 
GeneralGood control - perhaps the article needs a bit extra... Pin
robvon23-Mar-08 23:04
robvon23-Mar-08 23:04 
QuestionVS 2005 version available ? Pin
BillWoodruff22-Mar-08 4:26
professionalBillWoodruff22-Mar-08 4:26 
AnswerRe: VS 2005 version available ? Pin
Célio30-Mar-08 8:08
Célio30-Mar-08 8:08 
Generalfao Celio Re: VS 2005 version available ? Pin
BillWoodruff30-Mar-08 19:50
professionalBillWoodruff30-Mar-08 19:50 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.