简体   繁体   中英

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.

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.

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)).

您可以使用计时器,并将时间间隔设置为1秒,这将每秒触发一次并执行您需要的操作。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM