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

本文介绍了一种在Windows平台上实现跨线程消息传递的方法,主要通过使用'PeekMessage || GetMessage' API来自动创建消息循环,从而简化了消息处理流程。此外,还展示了如何使用PostThreadMessage API向非UI线程发送消息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

下面的代码是介绍如何在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. }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值