-----------------------------------------------------------------------------------------
In Windows development, it is inevitable to have interface-less programs in some scenarios. But we need to use the timer SetTimer in the Windows API to process some tasks regularly.
We all know that Windows is message-driven, and the timeout of the timer SetTimer is also driven by messages. The main thread of the Console process does not circulate messages, and Windows will not call our timeout callback function.
How do we deal with this situation?
We can actively add a message loop in the current thread to distribute the messages in the current thread, so that the timer can run normally.
In the Demo, I created a timer and set the timeout to 3 seconds. In the timeout callback function, I get the current time and output it, so that I can see the execution results more clearly.
#include <iostream>
#include <windows.h>
VOID CALLBACK TimerProc(HWND hwnd, UINT message, UINT iTimerID, DWORD dwTimer)
{
//获取系统时间
SYSTEMTIME time;
GetLocalTime(&time);
char dateTimeStr[200] = { 0 };
sprintf_s(dateTimeStr, "%d-%02d-%02d %02d:%02d:%02d", time.wYear, time.wMonth, time.wDay, time.wHour, time.wMinute, time.wSecond);
std::cout << dateTimeStr << std::endl;
}
int main()
{
UINT_PTR uTimerID = SetTimer(NULL, 0, 1000, TimerProc);// 3000三秒, TimerProc);
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
DispatchMessage(&msg);
}
KillTimer(NULL, uTimerID);
return 0;
}