11

How to create timer in WinApi (C++)?

sth
  • 222,467
  • 53
  • 283
  • 367
SomeUser
  • 1,976
  • 15
  • 42
  • 60

5 Answers5

11

Call the SetTimer function. This allows you to specify a callback function, or to have Windows post you a WM_TIMER message.

itowlson
  • 73,686
  • 17
  • 161
  • 157
  • 1
    as per nobugz - this will not work in console applications or non gui threads. threads must be pumping messages to generate SetTimer callbacks. – Chris Becke Jan 26 '10 at 21:33
  • SetTimer is not a high resolution (i.e., <20ms) timer. CreateTimerQueueTimer is better but consume more resources. –  Jun 20 '13 at 21:44
6

You cannot not know this if you write GUI code. Which makes it likely you want to use CreateTimerQueueTimer().

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • 2
    Yes, CreateTimerQueueTimer is your friend. Beware that the callback is executed on a threadpool thread so use proper locking. – Hans Passant Jan 24 '10 at 21:57
  • CreateWaitableTimer can also be used in console application. http://msdn.microsoft.com/en-us/library/windows/desktop/ms682492(v=vs.85).aspx – Li-chih Wu May 28 '14 at 05:57
4

SetTimer. A window handle is needed, and the timer will not be delivered if you aren't pumping messages.

John Knoeller
  • 33,512
  • 4
  • 61
  • 92
4

A Good Example for CreateTimerQueueTimer : Here

Another is HERE

Swanand
  • 4,027
  • 10
  • 41
  • 69
2

call the setTimer() Function. Suppose I called

SetTimer(hWnd,POST_CBIT_TIMER,500,NULL);

Call back function is

UINT nIdEvent ;//global member variable

case WM_TIMER:

if(nIDEvent == POST_CBIT_TIMER)
{

KillTimer(hParent,POST_CBIT_TIMER);


}
break;
The Hungry Dictator
  • 3,444
  • 5
  • 37
  • 53
sankar
  • 82
  • 5