MFC创建线程示例

MFC创建线程示例

AfxBeginThread()

创建现场的方法是AfxBeginThread()函数。

在【.CPP】文件定义一个全局变量,决定什么时候退出这个线程。

BOOL g_bWillExit=FALSE;

拖一个BUTTON按钮控件,【创建线程】(IDC_BUTTON_THREAD),绑定单击事件函数。

void CmyfirstmfcDlg::OnBnClickedButtonThread()
{
    g_bWillExit = FALSE;

    AfxBeginThread((AFX_THREADPROC)ThreadFunc, (LPVOID)this);  // this是主对话框的指针

    // 创建线程BUTTON按钮控件 禁止点击
    CButton *pButton = (CButton *)GetDlgItem(IDC_BUTTON_THREAD);
    pButton->EnableWindow(FALSE);
    // TODO: Add your control notification handler code here
}

回调函数


DWORD WINAPI ThreadFunc(PVOID param)
{
    while(g_bWillExit == FALSE)
    {
        if(MessageBox(NULL,_T("退出线程吗?"),_T("这是线程"),MB_YESNO)==IDYES)
        {
            // 创建线程BUTTON按钮控件 开启点击
            CmyfirstmfcDlg *pDlg = (CmyfirstmfcDlg*)param; //获取主对话框指针
            CButton *pButton = (CButton *)pDlg->GetDlgItem(IDC_BUTTON_THREAD); //主界面的按钮
            pButton->EnableWindow(TRUE);

            break;
        }
        
    }
    return 0;
}

退出线程

//线程退出
OnClose()
{
    g_bWillExit = TRUE;
}

猜你喜欢

转载自www.cnblogs.com/17bdw/p/10354929.html
今日推荐