Making a timer that doesn't freezes the app

Me again
I know that Sleep() is a basic windows.h function that just freezes the application for a specified time. During this time you just have to wait, you cannot press a button or even close the application. Is there a function that, while putting time intervals between some functions lets you realize other actions? If there's not, what would be the way of creating one? Handling processes? Using some timer object? Use the system timer? I hope my question is clear. Thanks for your suggestion.
If you are programming a Windows GUI, the simplest is to use a Windows timer. Read up about SetTimer() and KillTimer().
There are several ways to do this. The best approach depends on what kind of program you're making.

If you are using WinAPI's window managing system (ie: not the console), the message pump already does this. GetEvent() effectively sleeps until something interesting happens (ie: a key is pressed, mouse is moved... whatever), at which time the message gets sent to your message handler.

If you are looking to wait for a specified time in that environment, one way to do it would be to use the WM_TIMER message with the SetTimer function. SetTimer will send a WM_TIMER message to your window after X milliseconds have passed.

Another, slightly more complicated option that is typically used for games would be to re-adjust the message pump and manually check the time with GetTickCount or a similar timing function. Something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
while( program_is_running )
{
  // empty the message queue.  Process all pending messages
  while( PeekMessage( ... ) )
  {
    TranslateMessage(...);
    DispatchMessage(...);
  }

  // is it time for our action yet?
  if( signed(GetTickCount() - time_of_action) >= 0 )
  {
    // do the action
  }
  else
  {
    Sleep(1);  // otherwise, we can wait a bit longer
  }
}
Thanks man, now I get it. Thanks!
Topic archived. No new replies allowed.