C++: Setting up a Win32 timer

One of the most basic things in programming is setting up a timer. After a certain amount of time, it'll trigger a function you've defined.

To create a timer, we use the SetTimer() function.

UINT_PTR SetTimer(
HWND hWnd,
UINT_PTR nIDEvent,
UINT uElapse,
TIMERPROC lpTimerFunc
);

Now depending on your usage, the timer ID may vary.

  • If hWnd is NULL, then the timer ID is the return value.
  • If hWnd is valid, then the timer ID is nIDEvent.

The uElapse is the delay in millseconds.

Also note that you should kill a timer after you're done with it using KillTimer(timerID).

Depending on your application or DLL, you may choose between using a callback or receiving a WM_TIMER message.

Using a callback function

The callback function TIMERPROC is in the format of:

VOID CALLBACK TimerProc(
HWND hwnd,
UINT uMsg,
UINT_PTR idEvent,
DWORD dwTime
);

This method requires you to set up the callback function and pass it as lpTimerFunc.

Using the WM_TIMER message

Set a valid target for hWnd and set lpTimerFunc to NULL.

When the timer expires, the WM_TIMER message will be sent to your hWnd.

Process it in your WndProc() function and check wParam against the timer ID.

switch (uMsg) {
case WM_TIMER: {
if (wParam == YOUR_TIMER_ID) {
// Perform your timer code here
do_timer_stuff();

// Return 0 to indicate it has been processed.
return 0;
}

break;
}
}

[ Source ]

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog