PostThreadMessage to Console Application

The PostThreadMessage documentation is not clear about whether a message can be sent to a different process. I thought that the documentation was just incomplete, but I tried sending a PostThreadMessage to a console application. I nearly gave up, then finally got it working. The following sample can be used to verify that it is possible and it provides the basics for doing it yourself.

If this program is executed with no arguments, it will write a line with it's thread id and then wait for messages (in a "message loop"). If this program is executed with one argument, then it will assume that it is a thread id of another instance of itself and post a message to it, then quit. If the message sent is a WM_QUIT message instead of a WM_COMMAND message, then the message loop of the receiving instance will quit.

#include <windows.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
#pragma comment(lib, "user32")

int main(int argc, char *argv[], char *envp[]) {
	DWORD idThread;
	MSG Msg;
if (argc == 2) {
	idThread = atoi(argv[1]);
	if (!PostThreadMessage(idThread, WM_COMMAND, (WPARAM)0, (LPARAM)0))
		cout << GetLastError() << " PostThreadMessage error\n";
	return 0;
	}
cout << GetCurrentThreadId() << " thread id\n";
while (GetMessage(&Msg, NULL, 0, WM_USER)) {
	if (Msg.message == WM_COMMAND)
		cout << "WM_COMMAND\n";
	else
		cout << "Message: " << Msg.message << endl;
}
return 0;
}

See my Visual C++ Programmer Stuff page for more C++ stuff.