有时需要弹出一个messagebox提醒用户, messagebox会导致线程阻塞, 如果用户一直不点确定,则线程会一直阻塞在那里。 这个类实现了一个messagebox,如果用户在指定时间内没有点确定,则自动关闭该消息框。 class AutoCloseMsg { public: AutoCloseMsg(void); ~AutoCloseMsg(void); void ShowMsg(LPCTSTR szContext,LPCTSTR szTitle,unsigned long uTime = 30000); static DWORD __stdcall ShowMsgThread(void* pParam); private: LPCTSTR szContext; LPCTSTR szTitle; unsigned long uTime; HANDLE hWait; }; AutoCloseMsg::AutoCloseMsg(void) { hWait = CreateEventA(NULL,false,false,NULL); } AutoCloseMsg::~AutoCloseMsg(void) { } void AutoCloseMsg::ShowMsg(LPCTSTR szContext,LPCTSTR szTitle,unsigned long uTime) { this->szContext = szContext; this->szTitle = szTitle; this->uTime = uTime; unsigned long ulThreadId; HANDLE m_hThread = CreateThread(NULL, 0, ShowMsgThread, this, 0, &ulThreadId); if(NULL == m_hThread) { return ; } else { CloseHandle(m_hThread); } if (WAIT_TIMEOUT == WaitForSingleObject(hWait,uTime)) { HWND hwnd = ::FindWindow(NULL, szTitle); if(hwnd) { ::SendMessage(hwnd,WM_CLOSE,NULL,NULL); } } return; } DWORD AutoCloseMsg::ShowMsgThread(void* pParam) { AutoCloseMsg* acm = (AutoCloseMsg*)pParam; MessageBox(NULL,acm->szContext,acm->szTitle,MB_OK); SetEvent(acm->hWait); return 0; } int _tmain(int argc, _TCHAR* argv[]) { AutoCloseMsg automsg; automsg.ShowMsg(_T("5秒后消失"),_T("xxx消息提示"),5000); getchar(); return 0; }