Pasting into multiple text boxes

前端 未结 5 1413
小蘑菇
小蘑菇 2020-12-22 03:28

I have a .net application which includes search screen which has a panel with has three text boxes, each with a varying character lengths.

What I\

5条回答
  •  北海茫月
    2020-12-22 03:39

    As far as I can find there is no other sensible way of doing this than to capture the WM_PASTE event.

    Derive a class from TexBox and implement this method:

    using System.Windows.Forms;
    using System.ComponentModel;
    
    class TextBoxWithOnPaste : TextBox
    {
    
        public delegate void PastedEventHandler();
    
        [Category("Action")]
        [Description("Fires when text from the clipboard is pasted.")]
        public event PastedEventHandler OnPaste;
    
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == 0x302 && OnPaste != null) // process WM_PASTE only if the event has been subscribed to
            {
                OnPaste();
            }
            else
            {
                base.WndProc(ref m);
            }
        }
    }
    

    Then put three of those custom controls on your form, and assign the OnPaste event on all three textboxes to the same method, in this case I called it textPasted():

    private void textPasted()
    {
        String input = Clipboard.GetText();
    
        int l1 = textBoxWithOnPaste1.MaxLength;
        int l2 = textBoxWithOnPaste2.MaxLength;
        int l3 = textBoxWithOnPaste3.MaxLength;
    
        try
        {
            textBoxWithOnPaste1.Text = input.Substring(0, l1);
            textBoxWithOnPaste2.Text = input.Substring(l1, l2);
            textBoxWithOnPaste3.Text = input.Substring(l2, l3);
        }
        catch (Exception)
        { }
    
    }
    

    Since you implied "like a serial", I guessed you want the pasted string to be split among the textboxes. The code above is not perfect for that (try pasting a single space into the third text box after entering data manually in all three, so it would be nice if you knew in which textbox the text was pasted, for example by altering the event's parameters and that way sending the sender with it), but it basically works and I guess you can figure out the rest (you could use the Tag property to identify the textbox).

提交回复
热议问题