Sending Input to Background Program

Started by
4 comments, last by Arbaxas 18 years, 8 months ago
I'm currently trying to write a program that when I hit a certain key combo it will send certain keystroke to a window that DOESN'T have focus. Is this possible? I already have the stuff written to gather the input for the key combo, I just need to know how to send keystrokes to the underlying program. Would be excellent if anyone had some tips.
Advertisement
You definitly want to take a look at this old thread.
Thanks! Tested it with notepad and such and it works great.

If I have anymore complications I'll prolly be back.
I have ran into a prob...for what I am trying to do I would like to just send straight up keyboard input to the program itself without have to make it the foreground program.

Is there anyway to do this without having to send the input to a specific control?

Its like I want to emulate myself having it in the foreground and just hitting the key, not sending a message to a control.

Do you know how this can be done?
Let me just say this was a quick 2 minute put together, so I'm not sure how it will work in the long run, but for now this does work fine for me having notepad in the background.

#include <Windows.h>#include <iostream>using std::cout;using std::endl;int main( int argc, char* argv[] ){	HWND notepad = FindWindow("Notepad","Untitled - Notepad");	if( !notepad )	{	    cout << "Cannot find window!" << endl;	    return 0;	}	HWND control = FindWindowEx( notepad, 0, "Edit", "" );	if( !control )	{	    cout << "Cannot find control!";	    return 0;	}	PostMessage( control, WM_CHAR, 'A', WM_KEYDOWN );	PostMessage( control, WM_CHAR, 'B', WM_KEYDOWN );	PostMessage( control, WM_CHAR, 'C', WM_KEYDOWN );	return 0;}


I'm sure you can do a little more research into more windows messages and such if needed as well for more advanced things such as ctrl + key or alt + key, etc.. Take a look at MSDN for that. I just glanced as this page for throwing this example together.

Now that takes care of the 1st issue you raised about the program being in the background. As for not sending it to a specific control, you can try not sending to a control and just the main window handle, but that is not guarnteed to work all the time. The reason is, when you run any program and type something, let's say in some field, that field is the 'current' place that messages are handeled though in the background. So if you don't send to a control, then it's like pressing keys on a program that no form has focus on, not all all processed because for that certain program, only so much can be handled. I'm sure you can send something like alt + s to notepad's main handle and it will bring up the save dialog, but other than that, you must specify the control you want to send messages to. Just the way Windows works to my knowldege. Good luck!
Cool, thanks again.

I think this will work for what I'm doing.

This topic is closed to new replies.

Advertisement