0

Hi Gurus of Greatness!

I'm working on an WinForms app that has a textbox that allows pasting of CSV text data, and does some formatting on it. I have the formatting I need in place. However, what I end up with is the raw pasted text (CSV) and the formatted text.

How can I intercept the pasted text, do my formatting, then append the text that's already in the textbox?

Here's my Ctrl+V code on the KeyDown event of the textbox:

void txtNote_KeyDown(object sender, KeyEventArgs e)
    {
        TextBox box = (TextBox)sender;
        if (e.Control && e.KeyCode == Keys.V)
        {
            string[] strtextlines = Clipboard.GetText().ToString().Split(new char[] { '\n' });

            strtextlines[0] = strtextlines[0].Replace("\r\n", "");
            string strtextheader = "||" + strtextlines[0].Replace(",", "||");
            strtextheader = strtextheader + "||\r\n";
            string strttextbody = "";
            for (int i = 1; i <= strtextlines.Length-1; i++)
            {
                strtextlines[i] = strtextlines[i].Replace("\r\n", "");
                strttextbody = strttextbody + "|" + textlines[i].Replace(",", "|");
                strttextbody = strttextbody + "|\r\n";
            }
            box.Text = box.Text + "\r\n" + strtextheader + strttextbody;
            }
    }
  • What if the user right clicks and selects paste?! Instead of trapping Ctrl-V, you should instead **Inherit** from TextBox and trap the WM_PASTE command which would cover both Ctrl-V and Right Click --> Paste. From that command you could grab the clipboard data, suppress the default behavior for paste, then modify the contents of the TextBox to whatever you want. [Here's an example](http://stackoverflow.com/a/32730857/2330053) to get you started. – Idle_Mind May 02 '17 at 22:40
  • I'm the only user and I live by keyboard...but thank you! And thank you, Rubens, for the pointer...That's perfect. :) – Chris Shenar May 02 '17 at 22:43

0 Answers0