粘贴到多个文本框中

时间:2012-01-23 12:49:23

标签: c# .net winforms textbox copy-paste

我有一个.net应用程序,其中包含一个具有三个文本框的面板的搜索屏幕,每个面板都有不同的字符长度。

当我从第一个框中调用 粘贴命令并将我的剪贴板粘贴到三个框中时,我想要做的是捕获框。

此功能类似于许多接受串行密钥和电话号码输入的现代应用程序。

5 个答案:

答案 0 :(得分:4)

捕获粘贴事件:

protected override void WndProc(ref Message m) {
    // Did paste occur?
    if (m.Msg == 0x302) {
        //Paste occurred, add your logic here
    }
    base.WndProc(ref m);
}

然后,访问Clipboard object以获取所需的文字。

答案 1 :(得分:4)

据我所知,没有其他合理的方法可以捕获WM_PASTE事件。

从TexBox派生一个类并实现此方法:

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);
        }
    }
}

然后在表单上放置其中三个自定义控件,并将所有三个文本框上的OnPaste事件分配给同一个方法,在本例中我称之为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)
    { }

}

由于你暗示“喜欢串口”,我猜你想要将粘贴的字符串拆分成文本框。上面的代码并不完美(尝试在所有三个中手动输入数据后将单个空格粘贴到第三个文本框中,因此如果您知道文本粘贴在哪个文本框中会很好,例如通过更改事件的参数这样就可以发送发件人了),但它基本上有效,我想你可以弄明白其余部分(你可以使用Tag属性来识别文本框)。

答案 2 :(得分:1)

您可以绑定按键事件,当您获得Ctrl + VCtrl + v时,您可以使用剪贴板中的值更新三个文本框的值。您可以在TextChanged事件关闭第一个文本框中执行此操作。

答案 3 :(得分:1)

您可以获取捕获的文本 String txt = Clipboard.GetText(); 并将其放在另一个文本框的“Text”属性中

答案 4 :(得分:0)

您可以增加框的字符数限制并注册TextChanged,如果粘贴(或打字)文本的跳转/剪切时间更长,则为TextBox

相关问题