向线程函数里面传递事件,可以使用CEvent,还可以向里面投递消息。因为投递消息时,可以带两个参数(wParam, lParam)这两个参数在使用时就会非常方便;
首先启动一个线程函数,这里使用的是MFC的,不是Win32的方式,注意要用到返回值
pThread = AfxBeginThread(MyControllingFunction, this);
线程函数的实现为:
(当收到消息时,将参数值的变化,显示在主界面上)
UINT MyControllingFunction( LPVOID pParam )
{
CTestDlg *pDlg = (CTestDlg *)pParam;
MSG msg;
while(1)
{
if (::PeekMessage(&msg, NULL,0,0, PM_REMOVE))
{
if (msg.message == WM_USER+1)
{
//命令
CString str;
str.Format("%d", (int)msg.wParam);
pDlg->SetWindowText(str);
}
}
}
return 0L;
}
随便在外面一个地方,向线程函数内投递消息:(模拟每次点击累加)
void CTestDlg::OnButton1()
{
static int k = 0;
// TODO: Add your control notification handler code here
pThread->PostThreadMessage(WM_USER+1, k++, 0);
}