Basic knowledge
How to use the SetTimer function
Method 1: When using under the console or where there is no window:
Sample code:
void CALLBACK TimerProc (HWND hWnd, UINT nMsg, UINT nTimerid, DWORD dwTime)
{
SYSTEMTIME sys;
GetLocalTime (& sys);
printf ("M / d / d d: d: d.d xingqi \ n", sys.wYear, sys.wMonth, sys.wDay, sys.wHour, sys.wMinute, sys.wSecond, sys.wMilliseconds, sys.wDayOfWeek);
}
void main ()
{
MSG msg;
SetTimer (NULL, 230,4000, (TIMERPROC) TimerProc);
while (GetMessage (& msg, NULL, NULL, NULL))
{
if (msg.message == WM_TIMER)
{
TranslateMessage (& msg);
DispatchMessage (& msg);
break; // It's best to have one here, otherwise it looks like Killtimer can't end the timer.
}
}
KillTimer (NULL, 230);
}
Lesson: At the beginning, I thought that there was no need to set a message loop, so there was no write loop, and as a result, the execution program immediately exited.
Method two:
Using the message mechanism provided by MFC, the following two functions are mainly used.
WINUSERAPI
UINT_PTR
WINAPI
SetTimer (
__in_opt HWND hWnd,
__in UINT_PTR nIDEvent,
__in UINT uElapse,
__in_opt TIMERPROC lpTimerFunc); // Set it to NULL, that is, use the system default callback function
WINUSERAPI
BOOL
WINAPI
KillTimer (
__in_opt HWND hWnd,
__in UINT_PTR uIDEvent);
If the last parameter of the SetTimer function is NULL, the timer event is processed by the WM_TIMER message processing function. The method for adding a handler function for the WM_TIMER message is to find the class to add a timer in the Class View of the VS2010 project, right-click, select Properties, display its property page, and then click the Messages button on the property page toolbar. The list lists all the messages, finds the WM_TIMER message, and adds a message processing function.
Note: If there is only a single SetTimer timer, you can respond to the WM_TIMER message during function processing, thereby adding message processing code.