user1143336
user1143336

Reputation: 259

How to make an infinite loop in c++? (Windows)

I need for a function to repeat every second. I've tried both

for (;;) {}

and

while(true){}

But when I run the compiled program, the function runs only once.

Sorry, here is the full function

#define WINDOWS_LEAN_AND_MEAN
#define _WIN32_WINNT 0x0500 
#include <windows.h> 
#include <iostream> 

// do something after 10 minutes of user inactivity
static const unsigned int idle_milliseconds = 60*10*1000;
// wait at least an hour between two runs
static const unsigned int interval = 60*60*1000;

int main() {

    LASTINPUTINFO last_input;
    BOOL screensaver_active;

    // main loop to check if user has been idle long enough
    for (;;) {
        if ( !GetLastInputInfo(&last_input)
          || !SystemParametersInfo(SPI_GETSCREENSAVEACTIVE, 0,  
                                   &screensaver_active, 0))
        {
            std::cerr << "WinAPI failed!" << std::endl;
            return EXIT_FAILURE;
        }

        if (last_input.dwTime < idle_milliseconds && !screensaver_active) {
            // user hasn't been idle for long enough
            // AND no screensaver is running
            Sleep(1000);
            continue;
        }

        // user has been idle at least 10 minutes
        HWND hWnd = GetConsoleWindow(); 
    ShowWindow( hWnd, SW_HIDE ); 
    system("C:\\Windows\\software.exe");
        // done. Wait before doing the next loop.
        Sleep(interval);
    }
}

This run only once instead of continue checking.

Upvotes: 0

Views: 3232

Answers (3)

Shaun07776
Shaun07776

Reputation: 1052

You could use a timer, and set the interval to be 1 sec, this would fire every second and do what you need.

Upvotes: 0

Tibi
Tibi

Reputation: 3875

Both loops, for (;;) and while(1) are used for infinite loops. This is how your program would look like:

for (;;) // or while(1), doesn't matter
{
    function();
    sleep(1000);
}

If this doesn't work for you, you will have to provide more code, because I don't see other reasons why it wouldn't work.

Oh, and I must say that the sleep() function is implemented differently on various platforms. You have to find if the value is in seconds or milliseconds in your toolkit (if sleep(1000) doesn't work, try sleep(1)).

Upvotes: 2

AlexTheo
AlexTheo

Reputation: 4184

while(true){
  //Do something
}

should work but normally you should avoid infinity loops instead do something like

bool isRunning = true;
while( isRunning ){
  //Do something
}

in this way you will be able to terminate the loop whenever you need it.

Upvotes: 2

Related Questions