您的位置:首页 > 编程语言 > C语言/C++

VC++基础 使用自定义消息实现线程间的通信

2010-12-22 20:37 501 查看
自定义消息和全局变量:

#define WM_USERMSG WM_USER+100//自定义消息
volatile int SpeedControl;//定义全局变量


线程体:

UINT ThreadFunc(LPVOID lpParam)									//线程函数
{
NumInfo* pInfo=(NumInfo*)lpParam;							//线程函数参数
int i=0;
CString str;
while(true)
{
if(SpeedControl==1)								//低速计数
{
str.Format("%d",i);
pInfo->pedit->SetWindowText(str);
Sleep(2000);
i++;
if((i%17)==0)//计数到了17的整数倍
{
::PostMessage(pInfo->hwnd,WM_USERMSG,0,0);			//向主线程发送消息
}
}
if(SpeedControl==2)								//高速计数
{
str.Format("%d",i);
pInfo->pedit->SetWindowText(str);
Sleep(250);
i++;
if((i%17)==0)//计数到了17的整数倍
{
::PostMessage(pInfo->hwnd,WM_USERMSG,0,0);			//向主线程发送消息
}
}
if(SpeedControl==0)								//暂停
{
str.Format("%d",i);
pInfo->pedit->SetWindowText(str);
Sleep(200);
}
}
return 0;
}


主线程接收消息:

LRESULT CMessageThreadDlg::OnMsg(WPARAM wParam,LPARAM lParam)
{
// TODO: Add your control notification handler code here
AfxMessageBox("当前计数器的计数为17的整数倍");//提示对话框
return true;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: