下面的代码是介绍如何在windows平台发消息到非UI线程.
主要是'PeekMessage || GetMessage' 这两个API的应用. 当他们被调用的时候,如果当前线程还没有消息循环,就会创建一个.
利用这个特性比自己手动的去创建一个消息循环要方便得多.
发消息主要是使用线程PostThreadMessage
#include <iostream>
#include <string>
#include "cassert"
#include "windows.h"
#include "process.h"
enum { MSG_TEST = WM_USER+100,MSG_EXIT };
unsigned __stdcall fun(void *param)
{
MSG msg;
while(true)
{
if(GetMessage(&msg,0,0,0)) //get msg from message queue
{
char * info = reinterpret_cast<char*>(msg.wParam);
bool keep_in_loop = true;
switch(msg.message)
{
case MSG_TEST:
std::cout << info << std::endl;
break;
case MSG_EXIT:keep_in_loop=false;
default: break;
}
if ( ! keep_in_loop )
}
}
std::cout << "out of loop" << std::endl;
return 0;
}
void main()
HANDLE hThread;
unsigned nThreadID;
//start thread
hThread = (HANDLE)_beginthreadex( NULL, 0, &fun, NULL, 0, &nThreadID );
UINT Msg = MSG_TEST;
const char * p = "MSG_TEST";
std::string commond;
std::cin >> commond;
if ( commond == "exit" )
Msg = MSG_EXIT;
BOOL bPostOK = PostThreadMessage(nThreadID,Msg,(WPARAM)p,0);
if ( ! bPostOK )
assert( false );
// the post event is to too early, please build msg loop first
// 'PeekMessage || GetMessage' will forced to build the msg loop, if it does not exist.