在一个mfc对话框中,通过“开启”和“停止”两个按钮,打开和关闭一个线程
时间: 2023-05-23 21:03:40 浏览: 68
非常好的问题!可以通过以下代码实现:
首先,在对话框类的头文件中定义一个线程句柄,同时定义一个线程函数:
```
class CMyDialog : public CDialogEx
{
// ...
private:
HANDLE m_hThread; // 线程句柄
static UINT MyThreadProc(LPVOID pParam); // 线程函数
};
```
接着,在对话框的OnInitDialog()函数中初始化线程句柄:
```
BOOL CMyDialog::OnInitDialog()
{
// ...
m_hThread = NULL; // 初始化线程句柄
return TRUE;
}
```
然后在按钮的响应函数中,实现线程的启动和停止:
```
void CMyDialog::OnBtnStart()
{
if (m_hThread == NULL)
{
// 创建线程
m_hThread = CreateThread(NULL, 0, MyThreadProc, this, 0, NULL);
}
}
void CMyDialog::OnBtnStop()
{
if (m_hThread != NULL)
{
// 结束线程
TerminateThread(m_hThread, 0);
CloseHandle(m_hThread);
m_hThread = NULL;
}
}
```
最后,实现线程函数MyThreadProc(),在其中编写需要在线程中运行的代码,比如:
```
UINT CMyDialog::MyThreadProc(LPVOID pParam)
{
CMyDialog* pDlg = (CMyDialog*)pParam;
// 线程循环
while (true)
{
// 线程工作内容...
// 暂停一段时间
Sleep(1000);
}
return 0;
}
```
现在,当用户点击"开启"按钮时,程序将创建一个新的线程,并在其中运行MyThreadProc()函数;当用户点击"停止"按钮时,程序将结束该线程。