12

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?

Davide Piras
  • 43,984
  • 10
  • 98
  • 147
cb1295
  • 733
  • 4
  • 18
  • 36
  • 2
    check this one: http://stackoverflow.com/questions/3446233/hook-on-default-paste-event-of-winforms-textbox-control – Davide Piras Oct 21 '11 at 16:40

2 Answers2

34

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);
    }
}
Irshad
  • 3,071
  • 5
  • 30
  • 51
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • Do I put this in the Program.cs or the Form1.cs? And do I need to call it some how? because it isn't working – cb1295 Oct 21 '11 at 17:12
  • 2
    You put this in a separate class. Compile. Drop the new control from the top of the toolbox onto your form. – Hans Passant Oct 21 '11 at 17:27
5

To intercept messages in textbox control, derive a class from TexBox and implement

class MyTB : System.Windows.Forms.TextBox
{

    protected override void WndProc(ref Message m)
    {
        switch (m.Msg)
        {

            case 0x302: //WM_PASTE
                {
                    AddressTextBox.Text = Clipboard.GetText().Replace(Environment.NewLine, " ");
                    break;
                }

        }

        base.WndProc(ref m);
    }

}

suggested here

Haris Hasan
  • 29,856
  • 10
  • 92
  • 122
  • If I put this in my Form1.cs I get the following error: Error Cannot access a non-static member of outer type via nested type and If I put into Program.cs It says that AddressTextBox does not exist in the current context. – cb1295 Oct 21 '11 at 17:14
  • 3
    Add a new class through project->Add New Item - class name it `MyTb`. When you will build the project the MyTB will appear in toolbox. You can place it on your Form. – Haris Hasan Oct 21 '11 at 17:27
  • Thanks for the detailed explanation, however your code didn't do the trick or I didn't use it correctly. Thanks anyways! – cb1295 Oct 21 '11 at 18:10