工作日志--mfcButton和线程

问题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);


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值