天天看點

windows平台發消息到非UI線程.

下面的代碼是介紹如何在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.

繼續閱讀