I> 采用线程 WaitForSingleObject
void ThreadFunc()//线程函数
{
while(TRUE){}
}
void CMFCtimeoutDlg::OnBnClickedButton3()
{
// TODO: 在此添加控件通知处理程序代码
HANDLE hThread;
DWORD ThreadID;
hThread=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)ThreadFunc,NULL,0,&ThreadID);
DWORD hResult = WaitForSingleObject(hThread, 5000);//等待5秒
CWnd * pWnd = this->GetDlgItem(IDC_STATIC_TEXT);
if(hResult == WAIT_OBJECT_0) { //调用成功
if(pWnd)
pWnd->SetWindowText(_T("调用成功"));
}else if (hResult == WAIT_TIMEOUT) { //超时
if(pWnd)
pWnd->SetWindowText(_T("超时"));
}else { //出错
if(pWnd)
pWnd->SetWindowText(_T("出错"));
}
}
II> 定时器
HANDLE g_hdlThread;
UINT_PTR g_ptrTimer;
DWORD WINAPI BlockThreadFun(LPVOID lParam)
{
while(true){
TRACE(_T("Block Thread... \n"));
}
return 0;
}
void CMFCtimeoutDlg::OnBnClickedButton1()
{
// TODO: 在此添加控件通知处理程序代码
//采用线程执行某个阻塞函数
DWORD ThreadID;
g_hdlThread=::CreateThread(NULL,0,BlockThreadFun,this,0,&ThreadID);
}
VOID CALLBACK TimerProc(HWND hwnd,UINT uMsg,UINT_PTR idEvent,DWORD dwTime)
{
DWORD code;
GetExitCodeThread(g_hdlThread, &code);
if(code == STILL_ACTIVE)
{
TerminateThread(g_hdlThread, 0);
}
::KillTimer(NULL,g_ptrTimer);
}
void CMFCtimeoutDlg::OnBnClickedButton2()
{
// TODO: 在此添加控件通知处理程序代码
// 解除阻塞
g_ptrTimer = ::SetTimer(NULL,TIMER_EVENT_ID,2000,TimerProc);
}