To create a timer in c++ on Windows we must invoke the SetTimer() method, defined in windows.h.

UINT_PTR SetTimer(
// handle to the window associated to the timer
HWND hWnd,
// Timer ID
UINT_PTR nIDEvent,
// Elapse time in milliseconds
UINT uElapse,
// callback method to invoke when the timer expires
TIMERPROC lpTimerFunc
);

The hWnd argument is the handle to a window: for semplicity we don’t use any Handle, so we set it to NULL.

The function always returns an uint that represents the ID of the timer. if hWnd is NULL, the second parameter will be ignored and we can’t directly set the timer ID, but it will be assigned from the function. We can check if the creation of the timer didn’t have any problem if the uint returned from the function it’s not zero. Instead, if hWnd is not null, the timer ID will be assigned from the nIDEvent parameter

Add a global variable (ok, it’s not a good programming pratice adding global variabile, but this is only an howto) where we can save the timer ID:

uint m_timerID;


Define the function to invoke when the timer is elapsed:

void CALLBACK OnTimer(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime)
{
	// Insert here the code to execute at OnTimer event
}

And insert the timer inizialization:

m_timerID = SetTimer(NULL, 1, (UINT)2500, (TIMERPROC)OnTimer);

I created a timer that will expires in 2,5 seconds.
To kill the timer we can call the function KillTimer():

KillTimer(NULL, m_timerID);

Another interesting method to use this function, is to pass the handle of a window at the hWnd parameter, and NULL at the lpTimerFunc parameter:

m_timerID = SetTimer(hWnd, TIMER_ID, (UINT)2000, (TIMERPROC)NULL);

In this case we don’t have any callback function to intercept the timer event, but we can always listen to the event adding a case to the window procedure:

case WM_TIMER:
switch (wParam)
{
	case TIMER_ID:
	// Insert here the code to execute when the timer expires
	return 0;
}

In this case we must remember that when we call KillTimer() we must pass to it the handle to the window

KillTimer(hWnd, m_timerID);

At “C++ Timer Class” you can find a wrapper class to these functions.

kick it on DotNetKicks.com


Se sei interessato a questo post, potresti anche provare a leggere:

  • No related posts