c++ - 如何在C++中进行无限循环? ( Windows )

标签 c++ windows loops

我需要一个每秒重复一次的函数。我都试过了

for (;;) {}

while(true){}

但是当我运行编译后的程序时,该函数只运行一次。

对不起,这里是完整的功能

#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);
    }
}

这只运行一次而不是继续检查。

最佳答案

while(true){
  //Do something
}

应该可以,但通常你应该避免无限循环而不是做类似的事情

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

这样你就可以在需要的时候终止循环。

关于c++ - 如何在C++中进行无限循环? ( Windows ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8961259/

相关文章:

C++ 模板 - 如何解压模板参数元组的元组?

c++ - 如何写入第二个控制台?

c++ - 为 WinSocks 和 *nix 制作非阻塞套接字

Java程序跳过for循环

java - for循环中奇怪的重复次数

C++ MFC - 代码执行失败而不在 CDialog::OnSize 事件 (GetWindowRect) 上引发运行时错误

windows - 我如何将 Pyqt 与 Enthought Canopy 一起使用

javascript - 为什么 Node.js(文件名)会导致 Windows 上的 Node.JS 出现问题?

windows - 为什么 ruby​​ 在 windows 上这么慢?

javascript - 如何在 React Native 上循环 MasonryList?