here you go, a solution using the control's own properties:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
labTotalCharacters.Text = richTextBox1.Text.Length.ToString();
labTotalWords.Text = richTextBox1.Text
.Split(new[]
{
' ', '\n','?', '!', '.',
':', ';', ',', ')', '(',
'[', ']', '{', '}'
},
StringSplitOptions.RemoveEmptyEntries).Length
.ToString();
labTotalLines.Text = richTextBox1.Lines.Length.ToString();
}
private void button2_Click(object sender, EventArgs e)
{
int selstart = richTextBox1.SelectionStart;
int sellength = richTextBox1.SelectionLength;
richTextBox1.SelectionFont
= new Font(richTextBox1.Font, FontStyle.Bold);
richTextBox1.SelectionStart = richTextBox1.SelectionStart +
richTextBox1.SelectionLength;
richTextBox1.SelectionLength = 0;
richTextBox1.SelectionFont = richTextBox1.Font;
richTextBox1.Select(selstart, sellength);
}
}
I've added some extra counters plus a formatting test to show rich formatting does not affect the counts and deleting works as expected.
My Test Text (with bold selected text) is:
I have a RichTextBox that I am trying to manage the number of characters
in a line when I press the backspace key while entering data.
Because I am using rtbInfo_TextChanged to manage the number of Lines
and the TextLength.
Here are the property settings for the rtbInfo.
No Scroll Bars
Size 347 by 120
Word Wrap is False
Font 10.8. Bold
Mac Length 135
Total Text Characters: 352
Total words: 66
Total Lines: 10