C# – Capture text before pasting it into a TextView

Capture text before pasting it into a TextView… here is a solution to the problem.

Capture text before pasting it into a TextView

I have a TextView and

when pasting something from the clipboard, I need to intercept that text and preprocess it a bit before it appears in the TextView.

I tried listening to the “PasteClipboard” event, but it didn’t give me a way to modify the incoming text. and the “textview. Buffer.Changed” event.

Thanks in advance.

Solution

As far as I know, your best bet is to post-process the text after it has been inserted – the InsertText event on TextBuffer has parameters that tell you the position and size of the inserted text, so you can delete, process, and reinsert it. You certainly want to avoid capturing 1 character insertion (keystroke) and your own reinsertion, but this is trivial.

The only other option I can think of is to reimplement paste support, by capturing paste key commands, middle clicks, etc. – but note that command keys can be overridden in the user’s gtkrc file, so implementing this correctly can get hairy.

It may also be worth asking in the #gtk+ IRC channel on irc.gnome.org.

Related Problems and Solutions