3

When I try to send text from my RichTextBox to Notepad++ it only sends the first letter of the text. So if I had in my text box Send this to Notepad++ in Notepad++ all that would show up is S.

Here is my code

[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);
        }
    }
AlG
  • 14,697
  • 4
  • 41
  • 54
Jdean Smith
  • 33
  • 1
  • 3
  • CharSet = CharSet.Unicode. Standard advice: use UI automation to avoid getting these details wrong. System.Windows.Automation namespace. – Hans Passant Feb 22 '17 at 21:51

1 Answers1

5

You are running into a string encoding issue. Strings in .NET are UTF-16 little-endian strings. The string "Send" in UTF-16 is actually the bytes S{0}e{0}n{0}d{0}{0}{0}. Your declaration of SendMessage is using the ANSI string method. There are a number of ways to solve this. Here's one: Explicitly use the UTF-16 form by changing SendMessage to SendMessageW.

[DllImport("User32.dll")]
public static extern int SendMessageW(IntPtr hWnd, int uMsg, int wParam, string lParam);
Michael Gunter
  • 12,528
  • 1
  • 24
  • 58
  • Great. There are also a number of other options using some attributes of `DllImport` and the `MarshalAs` attribute (on the parameter). But this is the most concise. Don't forget to mark my answer as accepted. :) – Michael Gunter Feb 22 '17 at 21:38
  • I'd like to mark your answer as accepted but sadly I'm not the one who posted the question :p – Natalie Perret Feb 22 '17 at 21:39
  • Ok for some reason when I compile and run my program on my Windows 8.1 machine using Visual Studio 2015 it does not do anything, but when I use my Windows 10 machine to compile and run the program it works. Is there something different needed for Windows 8.1 from Windows 10 – Jdean Smith Feb 23 '17 at 03:42