windows平台发消息到非UI线程.

下面的代码是介绍如何在windows平台发消息到非UI线程. 
主要是'PeekMessage || GetMessage' 这两个API的应用. 当他们被调用的时候,如果当前线程还没有消息循环,就会创建一个.
利用这个特性比自己手动的去创建一个消息循环要方便得多. 
发消息主要是使用线程PostThreadMessage

  1. #include <iostream>
  2. #include <string>
  3. #include "cassert"
  4. #include "windows.h"
  5. #include "process.h"

  6. enum { MSG_TEST = WM_USER+100,MSG_EXIT };

  7. unsigned __stdcall fun(void *param)
  8. {
  9.     MSG msg;

  10.     while(true)
  11.     {
  12.         if(GetMessage(&msg,0,0,0)) //get msg from message queue
  13.         {
  14.             char * info = reinterpret_cast<char*>(msg.wParam);
  15.             bool keep_in_loop = true;
  16.             switch(msg.message)
  17.             {
  18.             case MSG_TEST:
  19.                 std::cout << info << std::endl;
  20.                 break;
  21.             case MSG_EXIT:keep_in_loop=false;
  22.                 std::cout << info << std::endl;
  23.                 break;
  24.             default: break;
  25.             }


  26.             if ( ! keep_in_loop )
  27.             {
  28.                 break;
  29.             }
  30.         }
  31.     }
  32.     std::cout << "out of loop" << std::endl;
  33.     return 0;
  34. }


  35. void main()
  36. {
  37.     HANDLE hThread;
  38.     unsigned nThreadID;

  39.     //start thread
  40.     hThread = (HANDLE)_beginthreadex( NULL, 0, &fun, NULL, 0, &nThreadID );

  41.     while(true)
  42.     {
  43.         UINT Msg = MSG_TEST;
  44.         const char * p = "MSG_TEST";

  45.         std::string commond;
  46.         std::cin >> commond;
  47.         if ( commond == "exit" )
  48.         {
  49.             Msg = MSG_EXIT;
  50.         }

  51.         BOOL bPostOK = PostThreadMessage(nThreadID,Msg,(WPARAM)p,0);
  52.         if ( ! bPostOK )
  53.         {
  54.             assert( false );
  55.             // the post event is to too early, please build msg loop first
  56.             // 'PeekMessage || GetMessage' will forced to build the msg loop, if it does not exist.
  57.         }
  58.     }
  59. }

原文地址:https://www.cnblogs.com/lidabo/p/3434849.html