您的位置:首页 > 其它

MFC 线程消息传递问题二---两个线程之间进行消息的传递

2013-12-02 14:35 295 查看
在接受消息的线程中进行设置消息映射表来实现消息的处理

负责发送消息的线程在线程的run函数中进行消息的发送:

 //线程之间进行消息传递设置

 CTManageThread* pDealThread = newCTManageThread();

 pDealThread->CreateThread();

 BOOL ret = ::PostThreadMessage(pDealThread->m_nThreadID,WM_USER_THREADEND, 0,0);//把消息传送到指定ID的线程,不等待线程对消息的处理就会立即返回

 

 

这样在接受消息的线程中需要的是在线程执行函数体中进行获取消息并进行消息的转换和派遣:

BEGIN_MESSAGE_MAP(CTManageThread, CWinThread)

 ON_THREAD_MESSAGE(WM_USER_THREADEND,OnManageMess)//添加的消息映射

 //ON_WM_TIMER()

 //ON_COMMAND()

END_MESSAGE_MAP()

void CTManageThread::OnManageMess(WPARAM wParam, LPARAMlParam)

{

  ::OutputDebugString(_T("ON_THREAD_MESSAGEis  runing \r\n"));

}

UINT CTManageThread::TestManageThread(LPVOID pParam)

{//创建线程

 CTManageThread* pDealThread =(CTManageThread*)pParam;

 

 pDealThread->dealMessage();

 return TRUE;

}

void CTManageThread::dealMessage()

{

 MSG msg = {0};

 do

 {

  ::GetMessage(&msg, NULL,0,0);//从消息队列中进行检索有效的消息

  CString str;

  str.Format(_T("%d, 0x%x\r\n"),msg.message, msg.message);

  OutputDebugString(str);

  //this->PreTranslateMessage(&msg);//对于窗体和线程之间来说这个函数更适合,这是对于内部进行判断,然后如果内部没有的话就会给全局的消息翻译函数TranslateMessage

  //::TranslateMessage(&msg);
  this->DispatchThreadMessage(&msg);//对于线程之间进行消息传递的,这个函数更加适合

  CTime t =CTime::GetCurrentTime();

  CString strTime;

  strTime.Format(_T("Deal :d:d:d\r\n"), t.GetHour(), t.GetMinute(), t.GetSecond());

  OutputDebugString(strTime);

  ::Sleep(2000);

 }while(1);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: