Introduction
Creating a separate thread in your application in order to execute some time consuming operations is very simple. You just call AfxBeginThread()
with the appropriate parameters and that's it. But Microsoft wants the controlling function either to be a global function or to be a static class member function; which in both cases means that you don't have access to your class member variables or methods from within the controlling function. This article shows you a little trick on how to do this and keep your source OO.
Step-by-Step
- Create your project as usual, add your dialogs, controls and all the stuff.
- Create your classes for the dialogs using Class Wizard, and assign variables to your controls.
- For the class you want to implement multithreading, edit the header file adding the following code:
static UINT StartThread (LPVOID param);
typedef struct THREADSTRUCT
{
CThreadDemoDlg* _this;
} THREADSTRUCT;
- In the implementation file for your class, add the following code:
UINT CThreadDemoDlg::StartThread (LPVOID param)
{
THREADSTRUCT* ts = (THREADSTRUCT*)param;
AfxMessageBox ("Thread is started!");
ts->_this->m_ctrl_progress.SetRange (0, 1000);
while (ts->_this->m_ctrl_progress.GetPos () < 1000)
{
Sleep(500);
ts->_this->m_ctrl_progress.StepIt ();
}
return 1;
}
void CThreadDemoDlg::OnStart()
{
THREADSTRUCT *_param = new THREADSTRUCT;
_param->_this = this;
AfxBeginThread (StartThread, _param);
}
- Now you can test your program!
Conclusion
I hope this will be helpful for you. I've been using CodeProject for a long time and this article is the first step for payback.