You currently have JavaScript disabled on your browser.

This website uses JavaScript, and This page needs JavaScript activated to work correctly.

Please active JavaScript on your browser and then refresh this page.

RichTextBox



example1

The RichTextBox control is found in the System.Windows.Forms namespace within the System.Windows.Forms.dll. In this blog post I am referring to the RichTextBox control that is available in C# .NET-Core (.NET 6.0) with Visual Studio 2022 (although this code example might still work OK with older .NET versions).

The RichTextBox control is used to create, display and edit rich text files (*.rtf) and/or plain ASCII text files (*.txt), and has built in LoadFile() and SaveFile() functions.

A RichTextBox control is an enhanced text box, which provides you with additional text formating options that are simply not available in a normal TextBox control. The RichTextBox control is capable of displaying formated text, data tables, and images.

The Find method provides overloads which allow you to find both strings of text as well as specific characters within text.

Similar to how a web page uses HTML script to define how a web page appears to the viewer, the RichTextBox control uses RTF script to define how the formated text document appears to the user. The RichTextBox control automatically handles creating and editing this RTF script for you, however it also provides methods which allows you to programmatically provide and control the RTF script yourself as well. Use the RTF property to Get or Set the text of the RichTextBox control, including all rich text format codes. Alternatively you can also use the TEXT property to Get or Set the current text displayed in the rich text box, and allow the RichTextBox control to automatically generate the RTF code using default settings.

The RichTextBox control is typically used to provide text manipulation and display features that are commonly found in more powerful word processing applications.

Unlike a TextBox control, the RichTextBox control does not have the same 64K character capacity limit.

The RichTextBox control also provides capabilities for Undo and Redo of the last edit operations done in the control. However, it should be noted that the Undo method does not work with the KeyPress or TextChanged events.

Use the DetectUrls property to appropriately display any hyperlinks contained within the control's text. You can handle the LinkClicked event to perform the task of launching the users web browser and navigating to the URL link that was clicked on.


Example Source Code

This example uses a RichTextBox control, along with:

To add the RichTextBox control to your form, you can double click on its name (i.e. RichTextBox) as listed in the Toolbox window panel within the Form editor window. Alternatively, you can single click on it and then drag and drop it onto your form, to position it more closer to where you want it to be positioned at. Once it is added to the form then it will appear on the forms surface area having default control values.

After you have added the RichTextBox control to your form, then once you select it then you can view and edit that objects property values in the Properties window within the Forms editor window, where you can then change the controls Name, Text, and other properties as you desire.

In the following example, I added a RichTextBox control to the Form, and then set its Anchor properties to Top, Left, Right, and Bottom. I then double clicked on its TextChanged event and SelectionChanged events to automatically create and link callback methods to those events into the Form's source code file.

I then added a ToolStrip control, and changed its default image size to (22,22). I then added child Buttons to the ToolStrip control objects Items property collection, renamed each child Button to their appropriate names so that I can more easily identify them in the source code, and then I double clicked on each Button to automatically create and link callback methods to their Click events into the Forms source code file. I adjusted the properties of the trailing buttons to better display for Text instead of for Images, and then updated their Text, Font, and BackColor properties as shown below, by individually selecting each Button and changing their property values in the Properties window, and repeating this step for each Button.

I then added all of the components, as shown below. For the ImageList component I modified its Images property to add local images that will be used with the ToolStriup Buttons, and set its ImageSize property to (22,22) to match the ToolStrip Buttons images size.

After adding the ToolTip component, I went back to the ToolStrip child Buttons and updated their "ToolTip on toolTip1" properties to match what that button is (i.e. New, Open, Save As, ect...), so that the program is more user friendly by providing meaningful tooltip's.

example2

After adding the controls and components to the Form as shown above, I then modified and enhanced upon the Form's source code file as shown below, to program each of the controls and components, and their callback methods:

 
// Copyright 2022 T&J Divisions, LLC	
// Designed and developed by Tim Tolbert
// All Rights Reserved
namespace TestProgram
{
    public partial class Form1 : Form
    {
        string currentFileNamePath = "";
		
        public Form1()
        {
            InitializeComponent();
        }
		
        private void Form1_Load(object sender, EventArgs e)
        {
            // init toolstrip button images
            toolStripButtonNew.Image = imageList1.Images[0];
            toolStripButtonOpen.Image = imageList1.Images[1];
            toolStripButtonSaveAs.Image = imageList1.Images[2];
            toolStripButtonUndo.Image = imageList1.Images[3];
            toolStripButtonRedo.Image = imageList1.Images[4];
            toolStripButtonCut.Image = imageList1.Images[5];
            toolStripButtonCopy.Image = imageList1.Images[6];
            toolStripButtonPaste.Image = imageList1.Images[7];

            // set filters
            openFileDialog1.Filter = "RichText (*.rtf)|*.rtf|Text (*.txt)|*.txt";
            saveFileDialog1.Filter = "RichText (*.rtf)|*.rtf|Text (*.txt)|*.txt";

            // set focus to richtextbox
            richTextBox1.Focus();
			
        }

        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {
            // update toolstrip buttons
            updateToolStripButtons();
        }

        private void richTextBox1_SelectionChanged(object sender, EventArgs e)
        {
            // update toolstrip buttons
            updateToolStripButtons();
        }

        private void toggleSelectionFontStyle(FontStyle targetStyle)
        { 
            // build list of font styles to use
            List<FontStyle> currentStyles = new List<FontStyle>();
			
            // bold
            if (targetStyle == FontStyle.Bold && richTextBox1.SelectionFont.Bold == false)
            {
                currentStyles.Add(FontStyle.Bold);
            }
            else if (targetStyle != FontStyle.Bold && richTextBox1.SelectionFont.Bold == true)
            {
                currentStyles.Add(FontStyle.Bold);
            }
            
            // italic
            if (targetStyle == FontStyle.Italic && richTextBox1.SelectionFont.Italic == false)
            {
                currentStyles.Add(FontStyle.Italic);
            }
            else if (targetStyle != FontStyle.Italic && richTextBox1.SelectionFont.Italic == true)
            {
                currentStyles.Add(FontStyle.Italic);
            }
            
            // underline
            if (targetStyle == FontStyle.Underline && richTextBox1.SelectionFont.Underline == false)
            {
                currentStyles.Add(FontStyle.Underline);
            }
            else if (targetStyle != FontStyle.Underline && richTextBox1.SelectionFont.Underline == true)
            {
                currentStyles.Add(FontStyle.Underline);
            }

            // re-apply new style('s) to selection
            if (currentStyles.Count == 0)
            {
                richTextBox1.SelectionFont = new Font(richTextBox1.SelectionFont, FontStyle.Regular);
            }
            else if (currentStyles.Count == 1)
            {
                richTextBox1.SelectionFont = new Font(richTextBox1.SelectionFont, currentStyles[0]);
            }
            else if (currentStyles.Count == 2)
            {
                richTextBox1.SelectionFont = new Font(richTextBox1.SelectionFont, currentStyles[0] | currentStyles[1]);
            }
            else if (currentStyles.Count == 3)
            {
                richTextBox1.SelectionFont = new Font(richTextBox1.SelectionFont, currentStyles[0] | currentStyles[1] | currentStyles[2]);
            }
        }

        private void toolStripButtonNew_Click(object sender, EventArgs e)
        {
            // new file
            currentFileNamePath = "";
            richTextBox1.Clear();

            // update toolstrip buttons
            updateToolStripButtons();
        }

        private void toolStripButtonOpen_Click(object sender, EventArgs e)
        {
            // open file
            // prompt to select an existing file
            openFileDialog1.FileName = currentFileNamePath;	
            if (openFileDialog1.ShowDialog(this) != DialogResult.OK) { return; }

            // copy file path
            currentFileNamePath = openFileDialog1.FileName;

            // load the selected file as current document
            if (openFileDialog1.FilterIndex == 1)
            {
                // load as rtf file
                richTextBox1.LoadFile(currentFileNamePath, RichTextBoxStreamType.RichText);
            }
            else if (openFileDialog1.FilterIndex == 2)
            {
                // load as txt file
                richTextBox1.LoadFile(currentFileNamePath, RichTextBoxStreamType.PlainText);
            }

            // update toolstrip buttons
            updateToolStripButtons();
        }

        private void toolStripButtonSaveAs_Click(object sender, EventArgs e)
        {
            // save file
            // prompt to specify file name and path to save as
            if (saveFileDialog1.ShowDialog(this) != DialogResult.OK) { return; }
            
            // copy file path
            currentFileNamePath = saveFileDialog1.FileName;

            // save the current document to file
            if (saveFileDialog1.FilterIndex == 1)
            {
                // save as rtf
                richTextBox1.SaveFile(currentFileNamePath, RichTextBoxStreamType.RichText);
            }
            else if (saveFileDialog1.FilterIndex == 2)
            {
                // save as txt
                richTextBox1.SaveFile(currentFileNamePath, RichTextBoxStreamType.PlainText);
            }
        }

        private void toolStripButtonUndo_Click(object sender, EventArgs e)
        {
            // undo
            if(richTextBox1.CanUndo == true)
            {
                richTextBox1.Undo();
            }
        }

        private void toolStripButtonRedo_Click(object sender, EventArgs e)
        {
            // redo
            if (richTextBox1.CanRedo == true)
            {
                richTextBox1.Redo();
            }
        }

        private void toolStripButtonBold_Click(object sender, EventArgs e)
        {
            // toggle bold
            toggleSelectionFontStyle(FontStyle.Bold);
        }

        private void toolStripButtonItalic_Click(object sender, EventArgs e)
        {
            // toggle italic
            toggleSelectionFontStyle(FontStyle.Italic);
        }

        private void toolStripButtonUnderline_Click(object sender, EventArgs e)
        {
            // toggle underline
            toggleSelectionFontStyle(FontStyle.Underline);
        }

        private void toolStripButtonForeColor_Click(object sender, EventArgs e)
        {
            // get current forecolor
            colorDialog1.Color = richTextBox1.SelectionColor;

            // prompt user to select a new color
            if(colorDialog1.ShowDialog(this) != DialogResult.OK) { return; }

            // update selection with new color
            richTextBox1.SelectionColor = colorDialog1.Color;

            // update toolstrip buttons
            updateToolStripButtons();
        }

        private void toolStripButtonBackColor_Click(object sender, EventArgs e)
        {
            // get current backcolor
            colorDialog1.Color = richTextBox1.SelectionBackColor;

            // prompt user to select a new color
            if (colorDialog1.ShowDialog(this) != DialogResult.OK) { return; }

            // update selection with new color
            richTextBox1.SelectionBackColor = colorDialog1.Color;

            // update toolstrip buttons
            updateToolStripButtons();
        }

        private void toolStripButtonCut_Click(object sender, EventArgs e)
        {
            // cut selected text
            richTextBox1.Cut();
        }

        private void toolStripButtonCopy_Click(object sender, EventArgs e)
        {
            // copy selected text
            richTextBox1.Copy();
        }

        private void toolStripButtonPaste_Click(object sender, EventArgs e)
        {
            // paste at cursor location
            richTextBox1.Paste();
        }
		
        private void toolStripButtonFont_Click(object sender, EventArgs e)
        {
            // change font
            // get current selections font
            fontDialog1.Font = richTextBox1.SelectionFont;
            
            // prompt user to select new font properties
            if(fontDialog1.ShowDialog(this) != DialogResult.OK) { return; }
            
            // update selection with new font
            richTextBox1.SelectionFont = fontDialog1.Font;
        }

        private void updateToolStripButtons()
        {
            // update button for bold
            if(richTextBox1.SelectionFont.Bold == true)
            {
                toolStripButtonBold.BackColor = Color.LightBlue;
            }
            else
            {
                toolStripButtonBold.BackColor = this.BackColor;
            }

            // update button for italic
            if (richTextBox1.SelectionFont.Italic == true)
            {
                toolStripButtonItalic.BackColor = Color.LightBlue;
            }
            else
            {
                toolStripButtonItalic.BackColor = this.BackColor;
            }

            // update button for underline
            if (richTextBox1.SelectionFont.Underline == true)
            {
                toolStripButtonUnderline.BackColor = Color.LightBlue;
            }
            else
            {
                toolStripButtonUnderline.BackColor = this.BackColor;
            }

            // update the buttons backcolor to show the current selections color values
            toolStripButtonForeColor.BackColor = richTextBox1.SelectionColor;
            toolStripButtonBackColor.BackColor = richTextBox1.SelectionBackColor;
        }
		
    }
}

When you run the above example and click type into the RichTextBox control, and click on the ToolStrip Button's, then you should see something similar to the following:


example3

example4

example5

example6

example7

Final Thoughts

Thank you for reading, I hope you found this blog post (tutorial) educational and helpful.


orangeStarorangeStarorangeStarorangeStarorangeStar  Overall rating of 5 from 1 members

User Comments






TJDivisions© 2022