How to send text to Notepad in C#/Win32?

    [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 button1_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), "Edit", null);
            SendMessage(child, 0x000C, 0, textBox1.Text);
        }
    }

WM_SETTEXT=0x000c


You first have to find the child window where the text is entered. You can do this by finding the child window with the window class "Edit". Once you have that window handle, use WM_GETTEXT to get the text which is already entered, then modify that text (e.g., add your own), then use WM_SETTEXT to send the modified text back.


using System.Diagnostics;
using System.Runtime.InteropServices;

static class Notepad
{
    #region Imports
    [DllImport("user32.dll")]
    public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);

    [DllImport("User32.dll")]
    private static extern int SendMessage(IntPtr hWnd, int uMsg, int wParam, string lParam);

    //this is a constant indicating the window that we want to send a text message
    const int WM_SETTEXT = 0X000C;
    #endregion


    public static void SendText(string text)
    {
        Process notepad = Process.Start(@"notepad.exe");
        System.Threading.Thread.Sleep(50);
        IntPtr notepadTextbox = FindWindowEx(notepad.MainWindowHandle, IntPtr.Zero, "Edit", null);
        SendMessage(notepadTextbox, WM_SETTEXT, 0, text);
    }
}