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