Icemanind Icemanind -4 years ago 135
C# Question

Detecting a paste into a RichTextBox

Is there some way I detect or cause an event to fire whenever text is pasted into a RichTextBox? Or maybe there is already some kind of event that fires when text is pasted? This is Winforms C#, by the way.

Answer Source

Because not all people may use Ctrl+V and because there are other ways to get text into a text box (such as drag and drop), I went a different route, which I will share here in case anyone else is looking for a solution.

What I did was create a field in my class:

int _lastPosition = 0;

and in the TextChanged() event I added the following:

if (SelectionStart - _lastPosition > 2)
{
    // Text was pasted into text box
}
_lastPosition = SelectionStart;

I went under the assumption that if more then 2 characters were entered into the text box at a time, then text must have been pasted, because how else can someone input more then 2 characters at a time? So anyway, this worked for me. Thanks to everyone who tried to help.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download