Does Qt detect when the computer is falling asleep?

How can I detect when a user's computer enters sleep mode (closing the lid of a laptop, sleep mode due to inactivity, etc.)?

I need to do this to disable users TCP connection. Basically, we got a simple chat application in which we want to disconnect the user.

+6
source share
3 answers

There is no way to determine Qt when the computer goes into sleep mode or sleep mode. But there are some platform dependent methods.

On Windows, you can listen to the WM_POWERBROADCAST message in the WindowProc handler:

LRESULT WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { if (WM_POWERBROADCAST == message && PBT_APMSUSPEND == wParam) { // Going to sleep } } 

On linux, you can put the following shell script in /etc/pm/sleep.d, which runs the program with arguments. You can run the program and somehow notify your main application:

 #!/bin/bash case $1 in suspend) #suspending to RAM /Path/to/Program/executable Sleeping ;; resume) #resume from suspend sleep 3 /Path/to/Program/executable Woken ;; esac 

For OS X, you can see this .

+4
source

You need to use the QNetworkConfigurationManager class, available in Qt 4.7 and above.

The QNetworkConfigurationManager provides access to a network of configurations known to the system and allows applications to discover system capabilities (regarding network sessions) at runtime.

In particular, look at the void QNetworkConfigurationManager::onlineStateChanged(bool isOnline) signal void QNetworkConfigurationManager::onlineStateChanged(bool isOnline) .

0
source

You can use 2 QTimers. One timer to activate the slot every time period, and the second - time tracking. Something like that:

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

All Articles