Programmatically Paste Clipboard Text to a CMD Window (C# or C++)

To accomplish this, I have tried different approaches: posting WM_PASTE, SendKeys sending ctrl-v… None of the method seems to be working so well.

A friend from work suggested trying WM_COMMAND. Since Spy++ doesn’t work with cmd.exe, we had to use brute force to find the correct WPARAM for pasting.

The result is really simple, just one line code with C++:

 // hwnd is the window handle of a CMD window
 SendMessage(hwnd, WM_COMMAND, 0xfff1, 0);

And here’s the C# version with PInvoke:

 [DllImport("user32")]
 private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
 private const uint WM_COMMAND = 0x0111;
 SendMessage(hwnd, WM_COMMAND, (IntPtr)0xfff1, IntPtr.Zero);