我需要“修改”所有粘贴到 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 和通用控件的一个薄包装。它公开了 80% 的最有用的 API。另外 20% 经常被遗漏或没有以明显的方式暴露出来。我建议如果可能的话,放弃 WinForms 并转向 WPF,因为 WPF 似乎是一个更好的 .NET GUI 架构框架。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)