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

Dav*_*vid 8 c# winforms

我需要"修改"所有粘贴到TextBox文本中以某种结构化方式显示.我可以使用drag-n-drop,ctrl-v来完成它,但是如何使用默认上下文的菜单"粘贴"呢?

orj*_*orj 18

虽然我通常不会建议降低到低级别的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);
    }
}
Run Code Online (Sandbox Code Playgroud)

最终WinForms工具包不是很好.它是围绕Win32和Common Controls的薄薄包装器.它暴露了最有用的80%的API.其他20%经常缺失或不以明显的方式暴露.我建议尽可能远离WinForms和WPF,因为WPF似乎是一个更好的.NET GUI架构框架.