Skip to content

Instantly share code, notes, and snippets.

@Virtlink
Last active August 11, 2020 22:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Virtlink/8429401 to your computer and use it in GitHub Desktop.
Save Virtlink/8429401 to your computer and use it in GitHub Desktop.
Sends `Hello world!` to one instance of notepad that is currently running.
using System;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
namespace Virtlink
{
public sealed class Program
{
#region PInvoke
[DllImport("user32.dll")]
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);
#endregion
private const int WM_SETTEXT = 0x000C;
static void Main(string[] args)
{
// Get the 'notepad' process.
var notepad = Process.GetProcessesByName("notepad").FirstOrDefault();
if (notepad == null)
throw new Exception("Notepad is not running.");
// Find its window.
IntPtr window = FindWindowEx(notepad.MainWindowHandle, IntPtr.Zero, "Edit", null);
// Send some string.
SendMessage(window, WM_SETTEXT, 0, "Hello world!");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment