Just Code‎ > ‎

C# - Add/Send text to notepad process using user32.dll SendMessage from your application

posted Jan 13, 2012, 1:31 AM by Peter Henell   [ updated Jan 25, 2012, 5:13 AM ]
How to add text to another applications text fields from your application?

This is a simple example of starting a Notepad process and then adding text to it.
Will open a new Notepad.exe process and then add the text "Sending a message, a message from me to you" to the text area of notepad.

The constant 0x000c of SendMessage  is documented here  http://msdn.microsoft.com/en-us/library/windows/desktop/ms632644(v=vs.85).aspx .
The constant says SETTEXT which really means that the text in notepad will be replaced if you send more than one message using this constant.
using System;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics;

namespace SendMessageTest
{
    class Program
    {
        [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);



        static void Main(string[] args)
        {
            DoSendMessage("Sending a message, a message from me to you");
        }

     
        
        private static void DoSendMessage(string message)
        {
            Process notepad = Process.Start(new ProcessStartInfo("notepad.exe"));
            notepad.WaitForInputIdle();
            
            if (notepad != null)
            {
                IntPtr child = FindWindowEx(notepad.MainWindowHandle, new IntPtr(0), "Edit", null);
                SendMessage(child, 0x000C, 0, message);
            }
        }
    }
}

Resources:
Comments