https://www.cnblogs.com/yinble/archive/2013/04/01/2994157.html
demo功能:
demo界面为对话框,在主界面选择计算1到10或50或100的自然数的累加和,点击求和按钮后主线程创建计算线程,给计算线程发送WM_CACULATE消息,计算线程计算完得到结果后,给主线程发送WM_DISPLAY消息,结果以参数的形式发送过去,主线程显示求和结果。
主线程WM_DISPLAY消息响应函数:
afx_msg LRESULT OnDisplay( WPARAM wParam, LPARAM lParam); |
WM_DISPLAY消息映射:
BEGIN_MESSAGE_MAP(CMultiThread5DlgDlg, CDialogEx) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDC_RADIO1, &CMultiThread5DlgDlg::OnBnClickedRadio1) ON_BN_CLICKED(IDC_RADIO2, &CMultiThread5DlgDlg::OnBnClickedRadio2) ON_BN_CLICKED(IDC_RADIO3, &CMultiThread5DlgDlg::OnBnClickedRadio3) ON_BN_CLICKED(IDC_SUM, &CMultiThread5DlgDlg::OnBnClickedSum) ON_MESSAGE(WM_DISPLAY, OnDisplay) END_MESSAGE_MAP() |
计算线程WM_CACULATE消息响应函数:
afx_msg void OnCaculate( WPARAM wParam, LPARAM lParam); |
WM_CACULATE消息映射:
BEGIN_MESSAGE_MAP(CCaculateThread, CWinThread) ON_THREAD_MESSAGE(WM_CACULATE, OnCaculate) END_MESSAGE_MAP() |
当使用CWinThread类或者其子类的时候,必须用ON_THREAD_MESSAGE来代替ON_MESSAGE。
定义自定义消息:
#define WM_CACULATE WM_USER+1 #define WM_DISPLAY WM_USER+2 |
在主线程中声明一个计算线程类的对象指针来存储子线程,并通过这个指针来发送WM_CACULATE消息给计算线程
CCaculateThread* m_pCaculateThread; |
m_pCaculateThread = (CCaculateThread *)AfxBeginThread(RUNTIME_CLASS(CCaculateThread)); Sleep(500); m_pCaculateThread->PostThreadMessage(WM_CACULATE, m_Addend, NULL); |
计算线程给主线程发送WM_DISPLAY消息
::PostMessageA(( HWND )GetMainWnd()->GetSafeHwnd(), WM_DISPLAY, sum, NULL); |