Title: Display subscripts and superscripts in a RichTextBox in C#
A TextBox can only use a single font at a time so it can't display subscripts and superscripts, but a RichTextBox can do it. Simply use the control's Select method to select the text that should be a subscript or a superscript. Then set the control's SelectionCharOffset property to move the text up or down on the baseline. You may also want to make the subscripted or superscripted text use a slightly smaller font.
This example uses the following code to demonstrate subscripts and superscripts.
private void Form1_Load(object sender, EventArgs e)
{
rchEquation.Text = "2H2 + O2 = 2H2O\n32 + 42 = 52";
// A smaller font.
float font_size = rchEquation.Font.Size;
Font small_font = new Font(
rchEquation.Font.FontFamily,
font_size * 0.75f);
// Subscripts.
int[] subs = { 2, 7, 13 };
int offset = (int)(font_size * 0.5);
foreach (int position in subs)
{
rchEquation.Select(position, 1);
rchEquation.SelectionCharOffset = -offset;
rchEquation.SelectionFont = small_font;
}
// Superscripts.
int[] supers = { 17, 22, 27 };
foreach (int position in supers)
{
rchEquation.Select(position, 1);
rchEquation.SelectionCharOffset = +offset;
rchEquation.SelectionFont = small_font;
}
// Center.
rchEquation.Select(0, rchEquation.Text.Length);
rchEquation.SelectionAlignment = HorizontalAlignment.Center;
rchEquation.Select(0, 0);
}
The code first sets the RichTextBox control's text. It then creates a smaller font that has 0.75 times the size of the original font.
Next the code creates an array holding the positions of the characters that should be subscripted. (The first character has index 0.) The code calculates an offset size equal to half of the original font's size.
The program then loops through the subscript positions. For each position, the code uses the control's Select method to select the character at that position. It then sets the selected character's offset to the negative of the calculated offset value (negative offsets make subscripts), and it sets the selected character's font to the smaller font.
The code then repeats those steps for some other characters that should be made superscripts.
Next the program selects all of the text and centers it. It finishes by moving the selection position to the beginning of the text.
Download the example to experiment with it and to see additional details.
|