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

3 Replies to “Programmatically Paste Clipboard Text to a CMD Window (C# or C++)”

  1. As a follow-up, if anyone needs to paste into a Putty.exe window, the parameter is 0x0190 instead of 0xfff1. This was found through brute force… Other values also worked, but I chose that one since the decimal (400) seemed nice and round.

Leave a Reply

Your email address will not be published. Required fields are marked *