PostThreadMessage to Console Application


Click here to change the theme.

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  shows how it is used:

PostThreadMessage(idThread, WM_COMMAND, (WPARAM)0, (LPARAM)0));

Some programmers might think that we can't send a message to a console program because there is no message loop. Well we can create a message loop in a console program. It is possible to show a window in a console program. We don't need to create a window though if we use PostThreadMessage to send the message. PostThreadMessage uses a thread id, not a window handle.

PostThreadMessage.cpp (and stdafx.h) is a sample that can be used to verify that it is possible and it provides the basics for doing it yourself. The program will:

  • If there is no argument for it, call itself (passing its thread id) then wait for the new process to send messages
  • If there is an argument then it will assume the argument is a thread id and send a message to that thread followed by a WM_QUIT