PostThreadMessage发送进程间消息(对话框向控制台发消息,控制台也可有消息循环)

函数原型

BOOL PostThreadMessage(
    DWORD idThread,
    UINT Msg,
    WPARAM wParam,
    LPARAM lParam
);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

The PostThreadMessage function posts a message to the message queue of the specified thread. 
It returns without waiting for the thread to process the message.

一、新建一Win32 Console Application : Hello

#include <iostream>
#include <Windows.h>

using namespace std;

int main()
{
    MSG msg;
    while (::GetMessage(&msg, NULL, 0, 0))
    {
        switch(msg.message)
        {
        case WM_USER + 100:
            cout << "Hello Kitty" << endl;
            break;
        case WM_PAINT:
            cout << "WM_PAINT" << endl;
            break;
        default:
            break;
        }
    }

    return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

二、

新建一对话框程序Test,并在初始化对话框时调用CreateProcess启动第一步生成的Hello.exe程序

STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));

TCHAR szCommandLine[] = TEXT("Hello.exe");

if(!CreateProcess(NULL,           // No module name (use command line)
    szCommandLine,  // Command line
    NULL,           // Process handle not inheritable
    NULL,           // Thread handle not inheritable
    FALSE,          // Set handle inheritance to FALSE
    0,              // No creation flags
    NULL,           // Use parent's environment block
    NULL,           // Use parent's starting directory 
    &si,            // Pointer to STARTUPINFO structure
    &pi)            // Pointer to PROCESS_INFORMATION structure
    ) 
{
    return;
}

m_nThrdIdHello = pi.dwThreadId;

// Close process and thread handles
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

三、利用PostThreadMessage向Hello.exe的主线程发送消息

::PostThreadMessage(m_nThrdIdHello, WM_USER+100, 0, 0);
::PostThreadMessage(m_nThrdIdHello, WM_PAINT, 0, 0);

http://blog.csdn.net/hisinwang/article/details/45047861

原文地址:https://www.cnblogs.com/findumars/p/8306958.html