正如这个程序所证明的,TextChanged
当控件被发送WM_SETTEXT
消息时,事件确实会触发。
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
const uint WM_SETTEXT = 0x000C;
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, unit Msg,
IntPtr wParam, string lParam);
public Form1()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
MessageBox.Show(textBox1.Text);
}
private void button1_Click(object sender, EventArgs e)
{
SendMessage(textBox1.Handle, WM_SETTEXT, IntPtr.Zero,
textBox1.Text + ", " + textBox1.Text);
}
}
}
请注意,答案的原始版本过于复杂,使用SendMessage
如下:
static extern IntPtr SendMessage(IntPtr hWnd, unit Msg,
IntPtr wParam, IntPtr lParam);
因此必须执行手动编组:
IntPtr text = Marshal.StringToCoTaskMemUni(textBox1.Text + ", "
+ textBox1.Text);
SendMessage(textBox1.Handle, WM_SETTEXT, IntPtr.Zero, text);
Marshal.FreeCoTaskMem(text);
这个问题的评论(自动转换字符串 DllImport 参数与 Marshal.StringToCoTaskMemUni)说服我更新。