c# - Hook WinForms TextBox 控件的默认 "Paste"事件

标签 c# winforms

我需要“修改”所有粘贴到 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/

相关文章:

c# - pinvoke:如何释放 malloc 的字符串?

c# - 方向 rtl 在 wkhtml 到 pdf 中不起作用

c# - 是否可以使用 CSS 设计 C# 应用程序

c# - 蒙版文本框输入左对齐

c# - 使用 Linq/Lambda 将 DataTable 转换为字典

c# - 在大图像中查找 16x16 像素相同正方形的有效算法 - C#

c# - 使用 DataTable 将数据加载到 DataGridView 的进度条

vb.net - MessageBox.Show 不引发 HelpRequested 事件

c# - 隐藏扫描仪进度条窗口

c# - 如何防止在 ListView 中移动列?