可以在任意地方Sleep了,避免使用Sleep函数造成界面卡顿甚至崩溃问题
typedef struct { UINT iDelayTime; HANDLE delayEvent; }tDelay; UINT ThreadDelay(LPVOID pParam) { tDelay *delay = (tDelay*)pParam; Sleep(delay->iDelayTime); //等待一段事件后将事件设为有信号 SetEvent(delay->delayEvent); return 0; } void MyDelay(int iDelayTime) { //不需要延时 if (iDelayTime <= 0) { return; } tDelay *pDlay = new tDelay; pDlay->iDelayTime = iDelayTime; //初始化一个不自动复原初始值为false的事件 pDlay->delayEvent = CreateEvent(NULL, FALSE, FALSE, NULL); //创建线程 HANDLE m_threadDelay; m_threadDelay = AfxBeginThread(ThreadDelay, pDlay); MSG msg; //等待1毫秒,没有等到事件也返回 while (::WaitForSingleObject(pDlay->delayEvent, 1) == WAIT_TIMEOUT) { //没有收到事件消息时维持MFC消息正常运行不卡顿 if (::PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { ::TranslateMessage(&msg); ::DispatchMessage(&msg); } } CloseHandle(pDlay->delayEvent); }
原理是sleep时保持原有的消息循环正常运行