How to Send text to Notepad in C#

By FoxLearn 7/19/2024 2:11:22 AM   7.66K
To pass data to Notepad using a C# Windows Forms Application, you can follow these steps.

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

How to pass data to the notepad in C#

c# send text to notepad

To send text to a Notepad process using user32.dll in C# Windows Forms, you can use the SendMessage function to send messages directly to the Notepad window.

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#.

// External functions
[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)
    {
        // Find the Notepad window
        IntPtr child = FindWindowEx(proc[0].MainWindowHandle, new IntPtr(0), "Edit", null);
        // Send text to Notepad
        SendMessage(child, 0x00B1, 0, txtInput.Text);
        SendMessage(child, 0x00C2, 0, txtInput.Text);
    }
}

In this example, We will get an instance of notepad application, then use FindWindow to find the Notepad window, and SendMessage is used to send the text to the window.

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