Do an operation when computer goes to sleep



  • Hi all,

    I'm writing a program that has a timer. When the computer goes to sleep I need to save some datas in order to correct the timer's value when the computer awakes.

    Are there some signals that are generated when the computer goes to sleep?

    thanks in advance!


  • Moderators

    @Nosba Hi! Yes, there is a D-Bus signal for this, it's PrepareForSleep(), see: https://www.freedesktop.org/wiki/Software/systemd/logind/.


  • Qt Champions 2016

    @Nosba
    hi
    on windows, you can catch the WM_POWERBROADCAST
    Tested with following code:

    #include <QAbstractNativeEventFilter>
    #include <QAbstractEventDispatcher>
    #include <QDebug>
    #include <windows.h>
    class MyEventFilter : public QAbstractNativeEventFilter {
     public:
      virtual bool nativeEventFilter(const QByteArray& eventType, void* message, long*) Q_DECL_OVERRIDE {
        MSG* msg = static_cast< MSG* >( message );
    
        if (msg->message == WM_POWERBROADCAST) {
          switch (msg->wParam) {
            case PBT_APMPOWERSTATUSCHANGE:
              qDebug() << ("PBT_APMPOWERSTATUSCHANGE  received\n");
              break;
            case PBT_APMRESUMEAUTOMATIC:
              qDebug() << ("PBT_APMRESUMEAUTOMATIC  received\n");
              break;
            case PBT_APMRESUMESUSPEND:
              qDebug() << ("PBT_APMRESUMESUSPEND  received\n");
              break;
            case PBT_APMSUSPEND:
              qDebug() << ("PBT_APMSUSPEND  received\n");
              break;
          }
        }
        return false;
      }
    };
    

    and in mainwindow constructor
    QAbstractEventDispatcher::instance()->installNativeEventFilter(new MyEventFilter);

    When i issue
    rundll32.exe powrprof.dll,SetSuspendState 0,1,0
    it goes to sleep and i wake it again
    i get
    PBT_APMSUSPEND received
    PBT_APMRESUMESUSPEND received
    PBT_APMRESUMEAUTOMATIC received

    So seems to function.
    Tested on win 10 ONLY.



  • Hello,

    thank you all, I was looking for something that would allow me to save my data on any operating system, but it seems there are different solutions for each operating system. I'll have to write a class with conditional compilation to save my data.

    thank you all once again.


  • Qt Champions 2016

    @Nosba
    Yes its very platform bound.
    Also, if you need to support Vista,
    you need extra code as far as the MS docs is correct.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.