挂钩WinForms TextBox控件的默认“粘贴”事件

我需要“修改”所有粘贴到TextBox文本中以某种结构化方式显示。 我可以用drag-n-drop,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 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 { ///  /// The main entry point for the application. ///  [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和Common Controls的薄型包装器。 它暴露了最有用的80%的API。 其他20%经常缺失或不以明显的方式暴露。 我建议尽可能远离WinForms和WPF,因为WPF似乎是一个更好的.NET GUI架构框架。