我需要“修改”所有粘贴到 TextBox 中的文本,以便以某种结构化方式显示。我可以通过拖放、ctrl-v 来完成,但是如何使用默认上下文菜单“粘贴”来完成?
最佳答案
虽然我通常不建议使用低级别的 Windows API,而且这可能不是唯一的方法,但它确实可以解决问题:
using System;
using System.Windows.Forms;
public class ClipboardEventArgs : EventArgs
{
public string ClipboardText { get; set; }
public ClipboardEventArgs(string clipboardText)
{
ClipboardText = clipboardText;
}
}
class MyTextBox : TextBox
{
public event EventHandler<ClipboardEventArgs> Pasted;
private const int WM_PASTE = 0x0302;
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_PASTE)
{
var evt = Pasted;
if (evt != null)
{
evt(this, new ClipboardEventArgs(Clipboard.GetText()));
// don't let the base control handle the event again
return;
}
}
base.WndProc(ref m);
}
}
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var tb = new MyTextBox();
tb.Pasted += (sender, args) => MessageBox.Show("Pasted: " + args.ClipboardText);
var form = new Form();
form.Controls.Add(tb);
Application.Run(form);
}
}
归根结底,WinForms 工具包不是很好。它是 Win32 和公共(public)控件的精简包装器。它公开了 80% 最有用的 API。另外 20% 经常丢失或没有以明显的方式暴露。如果可能的话,我建议从 WinForms 转移到 WPF,因为 WPF 似乎是一个更好的 .NET GUI 架构框架。
关于c# - Hook WinForms TextBox 控件的默认 "Paste"事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3446233/