TextChanged event in RichTextBox

  • Thread starter Thread starter Scott Allaire
  • Start date Start date
S

Scott Allaire

I want to be able to track what a user changed in a RichTextBox. That
is I want to know what they added, deleted or changed and where that
text was located. I have a TextChanged EventHandler set up and it
gets called when I type something or delete something, but I don't
know how to extract the information I need from the EventArgs.

Can someone send me an example of how to do this?

Thanks.
 
* (e-mail address removed) (Scott Allaire) scripsit:
I want to be able to track what a user changed in a RichTextBox. That
is I want to know what they added, deleted or changed and where that
text was located. I have a TextChanged EventHandler set up and it
gets called when I type something or delete something, but I don't
know how to extract the information I need from the EventArgs.

What information would you need?
 
I want to capture what text added, deleted or changed and what the
offset of the text modified was.
 
Scott, here's an untested code:

private string deletedString=null;
private int deletedStart=0;
private int deletedLength=0;

private void richTextBox1_KeyDown(object sender,
System.Windows.Forms.KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.X | Keys.Control:
case Keys.Delete:
if(richTextBox1.SelectionLength>0)
{
deletedString=richTextBox1.SelectedText;
deletedStart=richTextBox1.SelectionStart;
deletedLength=richTextBox1.SelectionLength;
}
else
{
if(richTextBox1.Text!="")
{

deletedString=richTextBox1.Text.Substring(richTextBox1.SelectionStart, 1);
deletedStart=richTextBox1.SelectionStart;
deletedLength=1;
}
}
break;
case Keys.Back:
if(richTextBox1.SelectionLength>0)
{
deletedString=richTextBox1.SelectedText;
deletedStart=richTextBox1.SelectionStart;
deletedLength=richTextBox1.SelectionLength;
}
else
{
if(richTextBox1.SelectionStart>0)
{

deletedString=richTextBox1.Text.Substring(richTextBox1.SelectionStart-1, 1);
deletedStart=richTextBox1.SelectionStart-1;
deletedLength=1;
}
}
break;
case Keys.V | Keys.Control:
if(richTextBox1.SelectionLength>0)
{
deletedString=richTextBox1.SelectedText;
deletedStart=richTextBox1.SelectionStart;
deletedLength=richTextBox1.SelectionLength;

// Added text can be determined here by querying the
clipboard for text data
// addedStart will be richTextBox1.SelectionStart and
addedLength will be the
// length of the text data above, if any.
}
else
{
// Added text can be determined here by querying the
clipboard for text data
// addedStart will be richTextBox1.SelectionStart and
addedLength will be the
// length of the text data above, if any.
}
break;
}
// Trap printable characters here to determine added characters
}
 
Back
Top