在VC中需要短暂延时时,常常用Sleep()函数,但该函数会使程序卡顿,不再响应用户的鼠标点击等操作。如何让计算机既能短暂延时,又能响应其它操作呢?博文“VC中不卡的延时”(https://www.cnblogs.com/rogee/archive/2011/04/08/2009764.html)提供了一种很好的思路。经过测试,确实不错。下面是测试通过的代码,可以实现比较精确的延时,能精确到毫秒级。源代码如下,供参考:
void CTestDlg::OnBnClickedButtonDelay()
{
// TODO: Add your control notification handler code here
DWORD tm0 = 0, tm1 = 0;
tm0 = GetTickCount();//获取当前时间,单位为ms
while(1)
{
MSG msg;
while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{//PM_REMOVE:Messages are removed from the queue after processing by PeekMessage.
TranslateMessage(&msg);//translates virtual-key messages into character messages
DispatchMessage(&msg);//dispatches a message to a window procedure
}
tm1 = GetTickCount();//获取当前时间,单位为ms
if((tm1 - tm0) >= 10 * 1000)//延时10秒
break;
}
AfxMessageBox(_T("Delay 10s over."));
return;
}
补充一下,后来测试,好像时间还是不那么精确,对于延时稍长一点的,比较有效。如果延时时间很短,如只有几个毫秒的,还是直接用Sleep()函数好点。
参考:
[1]. “VC中不卡的延时”,https://www.cnblogs.com/rogee/archive/2011/04/08/2009764.html