Detailed usage of richtextbox in C

  • 2020-06-23 01:46:19
  • OfStack

C# USES RichTextBox in the same way as TextBox, except that RichText supports RTF documents in addition to TXT. This paper introduces the use method of RichTextBox in detail for your reference, specifically as follows:

1. Usage of RichTextBox

RichTextBox Find method
The RichTextBox control not only allows you to enter and edit text, but it also provides many features of a more advanced specified format that the standard TextBox control does not.

Grammar: RichTextBox
Description:
RichTextBox provides properties that allow you to specify formatting for any part of the text of this control. To change the format of the text, first select it. Only selected text can be formatted for characters and paragraphs. Using these properties, you can change the text to bold or italic, or change its color, and create superscripts and subscripts. You can adjust the formatting of paragraphs by setting left and right indentation and hanging indentation.

The RichTextBox control can open and save files in both rtf format and plain ASCII text format. You can read and write files directly using the methods of the controls (LoadFile and SaveFile), or open and save files using control properties such as SelRTF and TextRTF that are linked to the Visual Basic file input/output statements.

By using the OLEObjects collection, the RichTextBox control supports object embedding. Each object inserted into the control represents an OLEObject object. With such a control, you can create documents that contain other documents or objects. For example, you can create a document that has an embedded Microsoft Excel spreadsheet, or an Microsoft Word document, or another OLE object that has been registered in the system. To insert an object into an RichTextBox control, simply drag a file (such as in Windows 95 "Explorer"), or drag a highlighted area of a file used by another 1 application (such as Microsoft Word), and drop the content directly into the control.

The RichTextBox control supports clipboard and OLE drag-and-drop operations for OLE objects. When an object is pasted from the clipboard, it is inserted at the current insertion point. When an object is dragged and dropped onto the control, the insertion point tracks the movement of the mouse cursor until the object is inserted when the mouse button is released. This behavior is the same as Microsoft Word.

Using the SelPrint method, you can print all or part of the text of the RichTextBox control.

Because RichTextBox is a data-bound control, the Data control can bind it to the Binary or Memo fields of the Microsoft Access database, or to other database fields of the same capacity (such as the TEXT data type fields in the SQL server).

RichTextBox controls support almost all the properties, events, and methods used by the standard TextBox controls, such as MaxLength, MultiLine, ScrollBars, SelLength, SelStart, and SelText. For applications that can use the TextBox control, the RichTextBox control is also easy to use. Moreover, the RichTextBox control does not have the 64K character limit that the standard TextBox control 1 has.

Note that in order to use the RichTextBox control in your application, you must add the Richtx32.ocx file to your project. Therefore, when the application is released, the ES90en32.ocx file should be installed in the SYSTEM directory of Microsoft Windows.

2. RichTextBox instance code:


private void  Open the graphics file ToolStripMenuItem_Click(object sender, EventArgs e)
 {
   string NameFile;
   if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
   {
 NameFile = this.openFileDialog1.FileName;
 if (NameFile != "")
 {
   this.pictureBox1.Image = Image.FromFile(NameFile);
 }
   }
 }
private void  Open text file ToolStripMenuItem_Click(object sender, EventArgs e)
 {
   string Filename;
   pictureBox1.Visible = false;
   if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
   {
 Filename = openFileDialog1.FileName;
 if (Filename != "")
 {
   this.textBox1.Text = Filename;
   this.richTextBox1.LoadFile(@Filename, RichTextBoxStreamType.PlainText);
 }
   }
 }

// The constructor 
    this.textBox1.KeyPress += new KeyPressEventHandler(textBox1_KeyPress);
    this.textBox1.Validating += new CancelEventHandler(textBox1_Validating);
    this.richTextBox1.LinkClicked += new LinkClickedEventHandler(richTextBox1_LinkClicked);
 // Cancel or set in bold 
 private void button2_Click(object sender, System.EventArgs e)
 {
    Font oldFont = this.richTextBox1.SelectionFont;
    Font newFont;
    if (oldFont.Bold)
  newFont = new Font(oldFont,oldFont.Style & ~FontStyle.Bold);
    else
  newFont = new Font(oldFont,oldFont.Style | FontStyle.Bold);
    this.richTextBox1.SelectionFont = newFont;
    this.richTextBox1.Focus();
 }
 // Cancel or italicize 
 private void button7_Click(object sender, System.EventArgs e)
 {
    Font oldFont = this.richTextBox1.SelectionFont;
    Font newFont;
    if (oldFont.Italic)
  newFont = new Font(oldFont,oldFont.Style & ~FontStyle.Italic);
    else
  newFont = new Font(oldFont,oldFont.Style | FontStyle.Italic);
    this.richTextBox1.SelectionFont = newFont;
    this.richTextBox1.Focus();
 }
 // To cancel or underline 
 private void button8_Click(object sender, System.EventArgs e)
 {
    Font oldFont = this.richTextBox1.SelectionFont;
    Font newFont;
    if (oldFont.Underline)
  newFont = new Font(oldFont,oldFont.Style & ~FontStyle.Underline);
    else
  newFont = new Font(oldFont,oldFont.Style | FontStyle.Underline);
    this.richTextBox1.SelectionFont = newFont;
    this.richTextBox1
  .Focus();
 }
 // Cancel or center 
 private void button5_Click(object sender, System.EventArgs e)
 {
    if (this.richTextBox1.SelectionAlignment == HorizontalAlignment.Center)
  this.richTextBox1.SelectionAlignment = HorizontalAlignment.Left;
    else
  this.richTextBox1.SelectionAlignment = HorizontalAlignment.Center;
    this.richTextBox1.Focus();
 }
 private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
 {
    if((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar !=13) 
    {
  e.Handled = true;
    }
    else if(e.KeyChar == 13) 
    {
  TextBox txt = (TextBox)sender;
  if(txt.Text.Length > 0) 
    ApplyTextSize(txt.Text);
  e.Handled = true;
  this.richTextBox1.Focus();
    }
 }
 private void textBox1_Validating(object sender, CancelEventArgs e)
 {
    TextBox txt = (TextBox)sender;
    ApplyTextSize(txt.Text);
    this.richTextBox1.Focus();
  }
 // Change font size 
 private void ApplyTextSize(string textSize)
 {
    float newSize = Convert.ToSingle(textSize);
    FontFamily currentFontFamily;
    Font newFont;
    currentFontFamily = this.richTextBox1.SelectionFont.FontFamily;
    newFont = new Font(currentFontFamily, newSize);
    this.richTextBox1.SelectionFont = newFont;
 }
 // Open the web page 
 private void richTextBox1_LinkClicked(object sender, LinkClickedEventArgs e)
 {
    System.Diagnostics.Process.Start(e.LinkText);
 }
 // Open the file 
 private void button1_Click(object sender, System.EventArgs e)
 {
    try
    {
  this.richTextBox1.LoadFile(@"..\..\test.txt");
    }
    catch(System.IO.FileNotFoundException)
    {
  MessageBox.Show("File not found!");
    }
 }
 // Save the file 
 private void button6_Click(object sender, System.EventArgs e)
 {
    try
    {
  this.richTextBox1.SaveFile(@"..\..\test.txt");
    }
    catch(System.Exception err)
    {
  MessageBox.Show(err.Message);
    }
 }

3. Search text within RichTextBox:

1. Reload list:

Search the text of the RichTextBox control for the first instance of a character in the character list


public int Find(char[]);

The following example searches the contents of RichTextBox for characters passed to the method in the text parameter. If the contents of the text array are found in RichTextBox, the method returns the index of the value found; Otherwise, it returns -1. The example assumes that this method is in the class of Form, where the form contains an RichTextBox control named richTextBox1 and an Button control named button1 connected to the click event handler method defined in the example.

The following code:


private void button1_Click(object sender, System.EventArgs e)
{
   MessageBox.Show(FindMyText(new char[]{'D','e','l','t','a'}).ToString());
}
public int FindMyText(char[] text)
{
   // Initialize the return value to false by default.
   int returnValue = -1;
   // Ensure that a search string has been specified and a valid start point.
   if (text.Length > 0) 
   {
     // Obtain the location of the first character found in the control
     // that matches any of the characters in the char array.
     int indexToText = richTextBox1.Find(text);
     // Determine whether the text was found in richTextBox1.
     if(indexToText >= 0)
     {
       // Return the location of the character.
       returnValue = indexToText;
     }
   }
   return returnValue;
}

2. Search for strings in the text of the RichTextBox control.


public int Find(string);

From a specific starting point, the first instance of a character in the character list is searched in the text of the RichTextBox control.


 public int Find(char[], int);

Search for a string in the text of the RichTextBox control when applying specific options to the search.


 public int Find(string, RichTextBoxFinds);

The following example searches the entire contents of RichTextBox for the first instance of the search string passed into the method's text parameters. If the search string is found in RichTextBox, this method returns the true value and highlights the text; Otherwise return false. This example also specifies an option to match the case of the specified search string in the search. This example assumes that this method is placed in the class of Form and that the class contains an RichTextBox named richTextBox1.

The specific code is as follows:


public bool FindMyText(string text)
{
  // Initialize the return value to false by default.
  bool returnValue = false;
  // Ensure a search string has been specified.
  if (text.Length > 0) 
  {
    // Obtain the location of the search string in richTextBox1.
    int indexToText = richTextBox1.Find(text, RichTextBoxFinds.MatchCase);
    // Determine if the text was found in richTextBox1.
    if(indexToText >= 0)
    {
     returnValue = true;
    }
  }
  return returnValue;
}

Searches for the first instance of a character in a character list in a text range of the RichTextBox control.


public int Find(char[], int, int);

When applying specific options to the search, search the text of the RichTextBox control for a string at a specific location within the control.


 public int Find(string, int, RichTextBoxFinds);

Searches the RichTextBox control text for strings within a text range within the control, with specific options applied to the search.


Related articles: