PostThreadMessage发送进程间消息

函数原型

BOOL PostThreadMessage(
    DWORD idThread,
    UINT Msg,
    WPARAM wParam,
    LPARAM lParam
);

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;
}

二、

新建一对话框程序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);

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

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

你可能感兴趣的:(C++,c,Win32)