覆盖粘贴到文本框 [英] Override Paste Into TextBox

查看:73
本文介绍了覆盖粘贴到文本框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在特定的文本框中,我想覆盖粘贴功能。将文本粘贴到该文本框中时,我希望它执行以下操作:

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, " ");

(从多行更改为单行)

我该怎么办?

推荐答案

有可能,您可以截获Windows的低级消息,即本机 TextBox 控件会告诉它要从剪贴板粘贴。 WM_PASTE 消息。当您使用键盘按Ctrl + V或使用上下文菜单的粘贴命令时都会生成。您可以通过重写控件的 WndProc()方法,按需要执行粘贴并将 not 传递给基类来捕获它。

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

这篇关于覆盖粘贴到文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆