Intercept the default Insert event for a TextBox WinForms control

I need to β€œmodify” all TextBox inserted into the text, which will be displayed in some structured way. I can do this using drag-n-drop, ctrl-v, but how to do it using the default context menu "Insert"?

+7
c # winforms
source share
1 answer

While I usually do not suggest abandoning the low-level Windows API, and this may not be the only way to do this, it does the trick:

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

Ultimately, WinForms toolkit is not very good. This is a thin shell around Win32 and Common Controls. It provides 80% of the API, which is most useful. The remaining 20% ​​is often absent or not exposed in an obvious way. I would suggest dropping WinForms and WPF if possible, since WPF seems to be the best architecture for the .NET GUI.

+16
source share

All Articles