Console Timer

Click here to change the theme.

The following console program works. It sets a timer using SetTimer then loops in a message loop. The message loop receives and processes WM_TIMER messages and the timer callback also is called for each time interval.

#define STRICT 1 
#include <windows.h>
#include <iostream.h>

VOID CALLBACK TimerProc(HWND hWnd, UINT nMsg, UINT nIDEvent, DWORD dwTime) {
cout << "Time: " << dwTime << '\n';

int main(int argc, char *argv[], char *envp[]) {
	int Counter=0;
	MSG Msg;
UINT TimerId = SetTimer(NULL, 0, 500, &TimerProc);
cout << "TimerId: " << TimerId << '\n';
if (!TimerId)
	return 16;
while (GetMessage(&Msg, NULL, 0, 0)) {
	if (Msg.message == WM_TIMER)
		cout << "Counter: " << Counter << "; timer message\n";
		cout << "Counter: " << Counter << "; message: " << Msg.message << '\n';
KillTimer(NULL, TimerId);
return 0;

I wrote this program after reading MS KB article Q102482 - INFO: SetTimer() Should Not Be Used in Console Applications which says that SetTimer() in a console application requires a separate thread. The Under The Hood article in the March 1997 issue of MSJ has a couple of sample console programs very similar to mine above. Like mine, they use SetTimer() without a separate thread.