Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SendMessage to Notepad++ in C#

Tags:

c#

sendmessage

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);
        }
    }
like image 992
Jdean Smith Avatar asked Apr 23 '26 19:04

Jdean Smith


1 Answers

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);
like image 88
Michael Gunter Avatar answered Apr 26 '26 08:04

Michael Gunter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!