Windows程序设计之控制台程序的定时器使用方法

一、函数原型

VOID CALLBACK TimerProc(
  HWND hwnd,         // handle to window
  UINT uMsg,         // WM_TIMER message
  UINT_PTR idEvent,  // timer identifier
  DWORD dwTime       // current system time
);

UINT_PTR SetTimer(
  HWND hWnd,              // handle to window
  UINT_PTR nIDEvent,      // timer identifier
  UINT uElapse,           // time-out value
  TIMERPROC lpTimerFunc   // timer procedure
);

二、示例代码

#include <iostream>
#include <Windows.h>
#include <tchar.h>

VOID CALLBACK TimerProc(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime)
{
	SYSTEMTIME sysTime;
	GetLocalTime(&sysTime);
	TCHAR buf[BUFSIZ] = { 0 };
	_stprintf_s(buf, BUFSIZ, TEXT("%04d-%02d-%02d %02d:%02d:%02d"), sysTime.wYear, sysTime.wMonth,
		sysTime.wDay, sysTime.wHour, sysTime.wMinute, sysTime.wSecond);
	_tprintf(TEXT("%s\n"), buf);
}

int main(void)
{
	SetTimer(NULL, 1, 1000, TimerProc);

	MSG msg;
	while (GetMessage(&msg, NULL, 0, 0))
	{
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}

	return 0;
}

Leave a Reply

Your email address will not be published.