【问题标题】:SendMessage to Notepad++ in C#在 C# 中向 Notepad++ 发送消息
【发布时间】:2017-02-22 21:26:04
【问题描述】:

当我尝试将文本从我的 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);
        }
    }

【问题讨论】:

  • CharSet = CharSet.Unicode。标准建议:使用 UI 自动化来避免弄错这些细节。 System.Windows.Automation 命名空间。

标签: c# sendmessage


【解决方案1】:

您遇到了字符串编码问题。 .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);

【讨论】:

  • 太棒了。还有许多其他选项使用DllImport 的某些属性和MarshalAs 属性(在参数上)。但这是最简洁的。不要忘记将我的答案标记为已接受。 :)
  • 我想将您的答案标记为已接受,但遗憾的是我不是发布问题的人:p
  • 好吧,当我使用 Visual Studio 2015 在我的 Windows 8.1 机器上编译和运行我的程序时,它什么也没做,但是当我使用我的 Windows 10 机器编译和运行程序时它可以工作. Windows 8.1 与 Windows 10 需要什么不同
猜你喜欢
  • 1970-01-01
  • 2010-09-14
  • 1970-01-01
  • 2017-03-20
  • 2020-01-13
  • 1970-01-01
  • 1970-01-01
  • 2011-07-26
  • 2019-09-16
相关资源
最近更新 更多