SendMessage WM_SETTEXT 到 TextBox 不会触发 TextChanged 事件

Mic*_*ick 0 c# winapi

我有代码获取文本框控件的句柄并使用 Windows API 来更改文本。更新文本时不会触发 TextChanged 事件。

有没有办法使用 Windows API 触发 TextBox.TextChanged 事件?

[更新]
我认为该事件未触发的原因是因为文本框句柄是通过 DCOM 接口发送的。该程序是用 c# 编写的 National Instruments TestStand shell,并使用 NI TestStand COM 对象来实现核心功能。在 TS 序列文件(一种 TS 脚本语言)中,我为文本框句柄创建了一个对象引用,并在 shell 表单的加载事件中使用 TS api 设置它。之后,我将句柄发送到我的 C# DLL。我使用 SendMessage 来更新文本框,效果很好。问题是 TextChanged 事件不会触发。

我尝试使用 TS 接口发送文本框和 TextChanged 委托,但无法使其工作。我认为通过 TS COM 对象执行此操作存在 AppDomain 问题。

Dav*_*nan 5

正如该程序所证明的,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, uint 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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,答案的原始版本过于复杂,并且使用了SendMessage如下内容:

static extern IntPtr SendMessage(IntPtr hWnd, unit Msg, 
  IntPtr wParam, IntPtr lParam);
Run Code Online (Sandbox Code Playgroud)

因此必须执行手动编组:

IntPtr text = Marshal.StringToCoTaskMemUni(textBox1.Text + ", "
  + textBox1.Text);
SendMessage(textBox1.Handle, WM_SETTEXT, IntPtr.Zero, text);
Marshal.FreeCoTaskMem(text);
Run Code Online (Sandbox Code Playgroud)

这个问题的评论(AutomaticcastingforstringDllImportargumentsvsMarshal.StringToCoTaskMemUni)说服我更新。