在 C# 中向 Notepad++ 发送消息

SendMessage to Notepad++ in C#

当我尝试将文本从我的 RichTextBox 发送到 Notepad++ 时,它只发送文本的第一个字母。因此,如果我在 Notepad++ 中的文本框 Send this to Notepad++ 中显示的所有内容都是 S.

这是我的代码

[DllImport("user32.dll", EntryPoint = "FindWindowEx")]
    public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
    [DllImport("User32.dll")]
    public static extern int SendMessage(IntPtr hWnd, int uMsg, int wParam, string lParam);
    private void button2_Click(object sender, EventArgs e)
    {

        Process[] notepads = Process.GetProcessesByName("notepad++");
        if (notepads.Length == 0) return;
        if (notepads[0] != null)
        {
            IntPtr child = FindWindowEx(notepads[0].MainWindowHandle, new IntPtr(0), "Scintilla", null);
            SendMessage(child, 0x000C, 0, RichTextBox1.Text);
        }
    }

您 运行 遇到了字符串编码问题。 .NET 中的字符串是 UTF-16 little-endian 字符串。 UTF-16 中的字符串 "Send" 实际上是字节 S{0}e{0}n{0}d{0}{0}{0}。您的 SendMessage 声明使用的是 ANSI 字符串方法。有很多方法可以解决这个问题。这是一个:通过将 SendMessage 更改为 SendMessageW.

来显式使用 UTF-16 格式
[DllImport("User32.dll")]
public static extern int SendMessageW(IntPtr hWnd, int uMsg, int wParam, string lParam);