您的位置:首页 > 其它

工作日志--mfcButton和线程

2015-07-05 17:03 363 查看
问题1:button的处理如果要消耗大量的时间,画面就会卡住

解决:可以在后台开一个线程,让消耗时间的工作放到后台线程完成。

增加后台线程有2种,有工作者线程和UI线程,本次使用UI线程

1、自己在dlg类中增加一个static函数,作为线程函数。

1.1、在.h文件中增加

static DWORD WINAPI MyThreadFunction( LPVOID pParam );
HANDLE m_pMyThread;
DWORD m_pMyThreadID;

1.2、在.cpp初始化函数中增加

m_pMyThreadID = 0;
m_pMyThread = CreateThread(NULL,0, MyThreadFunction, this, 0, &m_pMyThreadID);//要加this参数,否则线程开始就退出了。

1.3、在.cpp中增加线程函数

DWORD WINAPI CmfcButtonVs10Dlg::MyThreadFunction( LPVOID pParam )

{
CmfcButtonVs10Dlg* pdlg = (CmfcButtonVs10Dlg*)pParam;
if(pdlg == NULL)
{
printf("dlg is null, thread exit 1\n");
return 1;
}

MSG msg;
while(GetMessage(&msg, NULL, 0, 0) != -1)
{
printf("recv msg\n");
if(msg.message == WM_QUIT)
{
printf("MyThreadfunction recv Quit msg\n");
break;
}
else if(msg.message == WM_BUTTON_MSG)
{
//业务处理
}
else
{
printf("MyThreadfunction recv other msg\n");

}
}

return 0;

}

1.4、在button处理函数中向线程发消息

char* strTmp = new char[10];

sprintf(strTmp, "1111");

PostThreadMessage(m_pMyThreadID, WM_BUTTON_MSG, (WPARAM)strTmp, 0);

PostThreadMessage(m_pMyThreadID, WM_QUIT, 0, 0);

2、继承CWinThread线程。

2.1、在线程的.h中增加

afx_msg void OnButtonMessage(WPARAM wparam, LPARAM lparam);

2.2、在线程的.cpp中增加

ON_THREAD_MESSAGE(WM_BUTTON_MSG, &CMyThread::OnButtonMessage)

void CMyThread::OnButtonMessage(WPARAM wparam, LPARAM lparam)

{
//处理

}

2.3、在button函数中增加

char* strTmp = new char[10];

sprintf(strTmp, "1111");

PostThreadMessage(m_pMyThread->m_nThreadID, WM_BUTTON_MSG, (WPARAM)strTmp, 0);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: