[英]Override Paste Into TextBox
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? 我怎样才能做到这一点?
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. 这是可能的,您可以截取本机TextBox
控件获取的低级Windows消息,告知它从剪贴板粘贴。 The WM_PASTE
message. WM_PASTE
消息。 Generated both when you press Ctrl+V with the keyboard or use the context menu's Paste command. 使用键盘按Ctrl + V或使用上下文菜单的粘贴命令时生成。 You catch it by overriding the control's WndProc()
method, performing the paste as desired and not pass it on to the base class. 您可以通过覆盖控件的WndProc()
方法来捕获它,根据需要执行粘贴,而不是将其传递给基类。
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);
}
}
To intercept messages in textbox control, derive a class from TexBox and implement 要拦截文本框控件中的消息,从TexBox派生一个类并实现
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.