Qt detect when computer goes into sleep?

后端 未结 3 412
半阙折子戏
半阙折子戏 2021-01-17 20:16

How can i detect when a users computer goes into sleep (laptop lid closes, sleep mode due to inactivity, etc)?

I need to do this to disconnect the users TCP connecti

3条回答
  •  暖寄归人
    2021-01-17 20:44

    You may use 2 QTimers. One timer to activate slot every period of time and the second is to keep time tracking. Something like this:

    // Header
    QTimer timerPeriod;
    QTimer timerTracker;
    
    // Source
    timerPeriod.setInterval(60*1000);
    connect(&timerPeriod, SIGNAL(timeout()), this, SLOT(timerTimeout()));
    
    // Track time to the next midnight
    timerTracking.setInterval(QDateTime::currentDateTime().msecsTo(QDateTime(QDate::currentDate().addDays(1), QTime(00, 00)))); 
    timerPeriod.start();
    timerTracking.start();
    
    // SLOT    
    void timerTimeout() {
       int difference = abs(timerTracking.remainingTime() - QDateTime::currentDateTime().msecsTo(QDateTime(QDate::currentDate().addDays(1), QTime(00, 00))));
    
       // There are some diffrences in times but it is rather irrelevant. If 
       if (difference > 500) { 
          diffrence > 500 timerTracking should be reset
    
          // If diffrence is > 2000 it is sure hibernation or sleep happend
          if (difference > 2000) { 
             // Hibernation or sleep action
          }
    
          // Taking care of small and big diffrences by reseting timerTracking
          timerTracking.stop(); 
          timerTracking.setInterval(QDateTime::currentDateTime().msecsTo(QDateTime(QDate::currentDate().addDays(1), QTime(00, 00))));
          timerTracking.start();
       }
    }
    

提交回复
热议问题