工作线程默认是不会有消息队列的,工作线程中调用PeekMessage可以创建属于自己的消息队列。这样能使用在同一进程不同线程间的通讯。
PostThreadMessage
The thread to which the message is posted must have created a message queue, or else the call to PostThreadMessage fails. Use the following method to handle this situation.
-
Create an event object, then create the thread.
-
Use the WaitForSingleObject function to wait for the event to be set to the signaled state before calling PostThreadMessage.
-
In the thread to which the message will be posted, call PeekMessage as shown here to force the system to create the message queue.
PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE)
-
Set the event, to indicate that the thread is ready to receive posted messages.
同一进程的
// ThreadMessage.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <Windows.h>
#include <stdio.h>
#include <process.h>
#include <iostream>
using namespace std;
HANDLE g_event = NULL;
#define MSG_PRINT_CALL_TIME (WM_USER + 1)
#define MSG_END_THREAD (WM_USER + 2)
unsigned __stdcall SecondThreadFunc( void* pArguments )
{
MSG msg;
PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);
SetEvent(g_event);
int count = 0;
memset(&msg, 0, sizeof(MSG));
while (GetMessage(&msg, NULL, 0, 0))
{
switch (msg.message)
{
case MSG_PRINT_CALL_TIME:
cout<<"MSG_PRINT_CALL_TIME: "<<count<<endl;
count++;
break;
case MSG_END_THREAD:
cout<<"end thread"<<endl;
_endthreadex(0);
default:
cout<<"default"<<endl;
break;
}
}
return 0;
}
int main()
{
HANDLE hThread;
unsigned threadID;
g_event = CreateEvent(NULL, TRUE, FALSE, NULL);
if (NULL == g_event)
{
exit(1);
}
// Create the second thread.
hThread = (HANDLE)_beginthreadex( NULL, 0, &SecondThreadFunc, NULL, 0, &threadID );
WaitForSingleObject(g_event, INFINITE);
// MSG msg;
// memset(&msg, 0, sizeof(MSG));
// msg.message = MSG_PRINT_CALL_TIME;
PostThreadMessage(threadID, MSG_PRINT_CALL_TIME, (WPARAM)1, NULL);
PostThreadMessage(threadID, MSG_PRINT_CALL_TIME, (WPARAM)10, NULL);
PostThreadMessage(threadID, WM_USER, (WPARAM)10, NULL);
PostThreadMessage(threadID, MSG_END_THREAD, (WPARAM)10, NULL);
WaitForSingleObject( hThread, INFINITE );
// Destroy the thread object.
CloseHandle( hThread );
CloseHandle(g_event);
return 0;
}
不同进程的可以使用进程间通讯机制
WM_COPYDATA