tags:

views:

243

answers:

5

How does one "pause" a program in C++ on Win 32, and what libraries must be included?

+1  A: 
#include <windows.h>

Sleep(number of milliseconds);

Or if you want to pause your program while waiting for another program, use WaitForSingleObject.

IVlad
Error 2 error C3861: 'Sleep': identifier not found//despite #include <windows.h>
Chris_45
Can you post your code and what compiler are you using? This works on my machine with GCC: #include <windows.h>int main (){ Sleep(1000);}
IVlad
Ok you have to have the modern <cmath> and so on first in line and the oldies after these, is that a rule? At least it worked with that order.
Chris_45
Maybe you had an include file that somehow prevented windows.h from being included. Which headers did you include? I can't reproduce your error with <cmath> / <math.h> / <windows.h>. Generally, I put system headers first.
IVlad
Error include:#include <iostream> #include <windows.h>#include <cmath>#include <ctime>#include <ctime>using namespace std;
Chris_45
I'm not sure what the problem is, I can also run my sample program with those headers included in that order. I would suggest you put system headers at the top of your include list however, then standard headers and then your own custom / third party headers.
IVlad
Ok great thanks!
Chris_45
+2  A: 

If you are using boost, you can use the thread::sleep function:

#include <boost/thread/thread.hpp>
boost::system_time time = boost::get_system_time();
time += boost::posix_time::seconds(1);
boost::thread::sleep(time); 

Otherwise, you are going to have to use the win32 api:

#include <windows.h>
Sleep(1000);

And, apparently, C++0x includes this:

#include <thread>
std::this_thread::sleep_for(chrono::seconds(1));
John Gietzen
My gosh, that last line is ugly.
Steve Jessop
@Steve: My apologies.
John Gietzen
I don't blame you, unless you're on the C++ standard committee ;-)
Steve Jessop
+1  A: 

If you wish for the program to stay responsive while "paused", you need to use a timer event.

Tronic
actually, in Qt, if you want your program to be responsive while paused from a piece of code that is executed from the main thread, you dont want the timeout event of your timer to happen in the main thread as well.
yan bellavance
A: 

It depends on what type of program you are writing.

A console app can just call Sleep. A GUI app probably does not want to do this, as all the menus and widgets will go insensitive, and the app won't redraw itself during this period. Instead you need to do something like set yourself up a timer with a callback when it expires.

T.E.D.
A: 

Dont use a sleep function in your GUI if it is not provided by the framework you are working with. This could create referencing problems to data (specially in a thread that is not the main thread). This could freeze you GUI. Its not just a question of sleeping for a short time , use waitmutexes if you need to do that.

yan bellavance