定时器示例:
#include<tchar.h>
//Thecaptionofourmessagebox
TCHARg_szCaption[]=TEXT("TimedMessageBox");

//Howmanysecondswe'lldisplaythemessagebox
intg_nSecLeft=0;

//ThisisSTATICwindowcontrolIDforamessagebox
#defineID_MSGBOX_STATIC_TEXT0x0000ffff
//控件得值為即xFFFF
VOIDWINAPIMsgBoxTimeout(PVOIDpvContext,BOOLEANfTimeout)

{
//NOTE:Duetoathreadracecondition,itispossible(butveryunlikely)
//thatthemessageboxwillnotbecreatedwhenwegethere.
HWNDhwnd=FindWindow(NULL,g_szCaption);
if(hwnd!=NULL)

{
//Thewindowdoesexist;updatethetimeremaining.
TCHARsz[100];
wsprintf(sz,TEXT("Youhave%dsecondstorespond"),g_nSecLeft--);
SetDlgItemText(hwnd,ID_MSGBOX_STATIC_TEXT,sz);
if(g_nSecLeft==0)

{
//Thetimeisup;forcethemessageboxtoexit.
EndDialog(hwnd,IDOK);
}
}
else

{
//Thewindowdoesnotexistyet;donothingthistime.
//We'lltryagaininanothersecond.
}
}
intWINAPI_tWinMain(HINSTANCEhinstExe,HINSTANCE,PTSTRpszCmdLine,int)

{
chWindows9xNotAllowed();
//Howmanysecondswe'llgivetheusertorespond
g_nSecLeft=10;
//Createamultishot1secondtimerthatbeginsfiringafter1second.
HANDLEhTimerQTimer;
CreateTimerQueueTimer(&hTimerQTimer,NULL,MsgBoxTimeout,NULL,1000,1000,0);
//Displaythemessagebox
MessageBox(NULL,TEXT("Youhave10secondstorespond"),g_szCaption,MB_OK);
//Cancelthetimer&deletethetimerqueue
DeleteTimerQueueTimer(NULL,hTimerQTimer,NULL);
//Letusknowiftheuserrespondedorifwetimed-out.
MessageBox(NULL,(g_nSecLeft==0)?TEXT("Timeout"):TEXT("Userresponded"),TEXT("Result"),MB_OK);
return(0);
}
<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />
本文展示了一个使用定时器的示例代码,该程序通过创建一个1秒计时器,在指定时间内显示消息框并倒计时,到期后自动关闭。代码详细展示了如何设置定时器、更新消息框内容及取消定时器。
246

被折叠的 条评论
为什么被折叠?



