After a lot of research on Stackoverflow and google, it seems that it's difficult to send a combination of keystroke to a background window using it's handle. For example, I want to send CTRL + F. It seems that Sendmessage doesn't work, and sendinput isn't effective because the window needs the focus.
So the my last thought is about hooking: is there anyway to use that way to send combination?
Ok I found a workaround, but it doesn't work for all applications. Otherwise, it works with puTTY, the program I wanted to control with keystroke combination. And it works even if the application isn't focused. So I'm done now!
class SendMessage
{
[DllImport("user32.dll")]
public static extern IntPtr PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
public static void sendKeystroke()
{
const uint WM_KEYDOWN = 0x100;
const uint WM_KEYUP = 0x0101;
IntPtr hWnd;
string processName = "putty";
Process[] processList = Process.GetProcesses();
foreach (Process P in processList)
{
if (P.ProcessName.Equals(processName))
{
IntPtr edit = P.MainWindowHandle;
PostMessage(edit, WM_KEYDOWN, (IntPtr)(Keys.Control), IntPtr.Zero);
PostMessage(edit, WM_KEYDOWN, (IntPtr)(Keys.A), IntPtr.Zero);
PostMessage(edit, WM_KEYUP, (IntPtr)(Keys.Control), IntPtr.Zero);
}
}
}
}
I've written a couple of programs that send keystrokes to background windows, I generally implemented PostMessage/SendMessage. I documented all my findings here!
But you will basically be using a low level c call to put messages into the windows message queue to allow the application to pick up the key presses.
PostMessage
SendMessage
Please let me know if you have any questions, my library is written in C# and i'd be happy to share it. This method also allows for mouse use in a background window :)
All code was checked into GitHub: https://github.com/EasyAsABC123/Keyboard
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With