MFC界面线程通信与暂停,继续
void C界面线程Dlg::OnBnClickedButton1() { myThread = AfxBeginThread(RUNTIME_CLASS(MyThread)); } UINT __cdecl ThreadProc( LPVOID pParam ){//UINT = 无符号的int类型,4个字节,看平台决定 C界面线程Dlg* c = (C界面线程Dlg*)pParam;//强制类型转换 int i=0; while(true){ CString str; str.Format("%d\r\n",++i); //c->myEdit+=((++i)+"\r\n");//不能使用 c->myEdit+=str; ::SendMessage(c->GetSafeHwnd(), WM_MyMessage, 0,0);//发送了,如果 想在不是主线程的线程中操作窗口的话,就用发送消息 Sleep(1000); } return 0; } LRESULT C界面线程Dlg::OnMyMessage(WPARAM wParam, LPARAM lParam){//LRESULT == long UpdateData(FALSE);//把值更新到控件上 return 0; } void C界面线程Dlg::OnBnClickedButton2() { myThread = AfxBeginThread(ThreadProc,this);//必须用指针保存下来,不然方法运行完后,变量就不在了 } void C界面线程Dlg::OnBnClickedButton4() { ::SuspendThread(myThread->m_hThread);//这个是暂停线程 } void C界面线程Dlg::OnBnClickedButton3() { ::ResumeThread(myThread->m_hThread);//继续线程 } void C界面线程Dlg::OnBnClickedButton5() {/* CString a = "我是字符串1"; CString b = "我是字符串2";*/ //不能这样,因为他是存在与栈中的,方法完毕后,他会被销毁 CString* a = new CString("我是字符串1"); CString* b = new CString("我是字符串2"); //m_nThreadID这个是线程的ID ,MY_THREAD_MSG是消息 PostThreadMessage(myThread->m_nThreadID,MY_THREAD_MSG,(WPARAM)a,(LPARAM)b);//指针传递 }
主线程:
BOOL C界面线程App::PreTranslateMessage(MSG* pMsg) { // TODO: 在此添加专用代码和/或调用基类 if(pMsg->message == WM_USER+2){//说明是我们传递过来的消息 CString* a = (CString*)(pMsg->lParam); CString* b = (CString*)(pMsg->wParam); AfxMessageBox(*a);//之所以要加*号,不传递指针,是因为他的参数是一个const类型字符串常量 AfxMessageBox(*b); //记得删除CString a=NULL ; b=NULL; return TRUE; } return CWinApp::PreTranslateMessage(pMsg); }
子窗口DLG:
void myDialog::OnBnClickedButton1() { CString* a = new CString("我是子窗口1"); CString* b = new CString("我是子窗口2"); PostThreadMessage(AfxGetApp()->m_nThreadID,WM_USER+2,(WPARAM)a,(LPARAM)b); }
子线程:
// MyThread 消息处理程序 BOOL MyThread::PreTranslateMessage(MSG* pMsg) { // TODO: 在此添加专用代码和/或调用基类 if(pMsg->message == WM_USER+2){//说明是我们传递过来的消息 CString* a = (CString*)(pMsg->lParam); CString* b = (CString*)(pMsg->wParam); AfxMessageBox(*a);//之所以要加*号,不传递指针,是因为他的参数是一个const类型字符串常量 AfxMessageBox(*b); //记得删除CString a=NULL; b=NULL; return TRUE; } return CWinThread::PreTranslateMessage(pMsg); }


浙公网安备 33010602011771号