Use SetTimer in Console without graphical interface program

UpdateData(true); assign the value of the control to the member variable
UpdateData(false); assign the value of the member variable to the control
UpdateData; used to refresh the current dialog box
That is to say: after you use ClassWizard to establish the connection between the control and the variable: when you modify the value of the variable and want the dialog box control to update the display, you should call UpdateData(FALSE) after modifying the variable; if you If you want to know what the user entered in the dialog box, you should call UpdateData(TRUE) before accessing the variable.

-----------------------------------------------------------------------------------------

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;
}

Guess you like

Origin blog.csdn.net/aw344/article/details/131746468