Windows Forms: Send text to Notepad in C#

This article shows you how to pass data to the notepad using C#.NET Windows Forms Application.

To play the demo, you can drag the TextBox and Button from your visual studio toolbox to your winform, then you can layout your UI as shown below.

c# send text to notepad

To send text to notepad process using user32.dll in c#, you need to import the FindWindowEx and SendMessage methods from the Win32 API, then you can use the SendMessage function to send a string to another application in c#.

[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);

And don't forget to include the namespaces below.

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

Finally, Add code to handle the btnSend_Click event as shown below. In which, btnSend is the name of the Send button.

private void btnSend_Click(object sender, EventArgs e)
{
    Process[] proc = Process.GetProcessesByName("notepad");
    if (proc.Length == 0)
        return;
    if (proc[0] != null)
    {
        IntPtr child = FindWindowEx(proc[0].MainWindowHandle, new IntPtr(0), "Edit", null);
        SendMessage(child, 0x00B1, 0, txtInput.Text);
        SendMessage(child, 0x00C2, 0, txtInput.Text);
    }
}

We will get an instance of notepad application, then find window of notepad and use the SendMessage method to send data to another application.

Press F5 to run your project, then open the notepad application. Next, Enter a text value and click the Send button to send text to notepad using c# windows forms application.

You should open the notepad application when playing the demo. You can see the text you enter will send to the notepad application.

Related