C++: Setting up a Win32 timer

0 Comments

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.

1.UINT_PTR SetTimer(
2.  HWND hWnd,
3.  UINT_PTR nIDEvent,
4.  UINT uElapse,
5.  TIMERPROC lpTimerFunc
6.);

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:

1.VOID CALLBACK TimerProc(
2.  HWND hwnd,
3.  UINT uMsg,
4.  UINT_PTR idEvent,
5.  DWORD dwTime
6.);

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.

01.switch (uMsg) {
02.  case WM_TIMER: {
03.    if (wParam == YOUR_TIMER_ID) {
04.      // Perform your timer code here
05.      do_timer_stuff();
06. 
07.      // Return 0 to indicate it has been processed.
08.      return 0;
09.    }
10. 
11.    break;
12.  }
13.}

[ Source ]

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