勾上默认的"粘贴"的的WinForms TextBox控件事件 [英] hook on default "Paste" event of WinForms TextBox control
问题描述
我要修改所有粘贴到文本框的文本以某种结构化的方式显示。我可以拖放正下降,CTRL-V做,但如何与默认的上下文菜单粘贴呢?
I need to "modify" all pasted into TextBox text to be shown in some structured way. I can do it with drag-n-drop, ctrl-v, but how to do it with default context's menu "Paste"?
推荐答案
虽然我通常不建议下探至低级别的Windows API,这可能不会是这样做的唯一途径,但它确实做的伎俩:
While I would normally not suggest dropping to low level Windows API, and this may not be the only way of doing this, it does do 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);
}
}
最终的WinForms的工具不是很好。它是围绕Win32和公用控件薄十岁上下的包装。它暴露是最有用的API 80%。另外20%通常被丢失或在某种程度上是显而易见的不会露出。我建议从WinForms和WPF的,如果尽可能WPF似乎远动成为.NET图形用户界面更好的架构的框架。
Ultimately the WinForms toolkit is not very good. It is a thin-ish wrapper around Win32 and the Common Controls. It exposes the 80% of the API that is most useful. The other 20% is often missing or not exposed in a way that is obvious. I would suggest moving away from WinForms and to WPF if possible as WPF seems to be a better architected framework for .NET GUIs.
这篇关于勾上默认的&QUOT;粘贴&QUOT;的的WinForms TextBox控件事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!