Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override Paste Into TextBox

I want to override the paste function when in a specific textbox. When text is pasted into that textbox, I want it to execute the following:

AddressTextBox.Text = Clipboard.GetText().Replace(Environment.NewLine, " ");

(Changing from multiline to single)

How can I do this?

like image 655
cb1295 Avatar asked Oct 21 '11 16:10

cb1295


1 Answers

That's possible, you can intercept the low-level Windows message that the native TextBox control gets that tells it to paste from the clipboard. The WM_PASTE message. Generated both when you press Ctrl+V with the keyboard or use the context menu's Paste command. You catch it by overriding the control's WndProc() method, performing the paste as desired and not pass it on to the base class.

Add a new class to your project and copy/paste the code shown below. Compile. Drop the new control from the top of the toolbox onto your form, replacing the existing one.

using System;
using System.Windows.Forms;

class MyTextBox : TextBox {
    protected override void WndProc(ref Message m) {
        // Trap WM_PASTE:
        if (m.Msg == 0x302 && Clipboard.ContainsText()) {
            this.SelectedText = Clipboard.GetText().Replace('\n', ' ');
            return;
        }
        base.WndProc(ref m);
    }
}
like image 139
Hans Passant Avatar answered Sep 28 '22 02:09

Hans Passant