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!

  • @Nosba Hi! Yes, there is a D-Bus signal for this, it's PrepareForSleep(), see:

  • Lifetime Qt Champion

    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 {
      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) {
              qDebug() << ("PBT_APMPOWERSTATUSCHANGE  received\n");
              qDebug() << ("PBT_APMRESUMEAUTOMATIC  received\n");
            case PBT_APMRESUMESUSPEND:
              qDebug() << ("PBT_APMRESUMESUSPEND  received\n");
            case PBT_APMSUSPEND:
              qDebug() << ("PBT_APMSUSPEND  received\n");
        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

    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.

  • Lifetime Qt Champion

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

  • This topic is a few years old, but still appears to be the best approach (on Windows) in 2019.

    One important note:
    The MS docs state "An application should return TRUE if it processes this message."

    Based on experimentation, it seems that you should return true in your filter on every WM_POWERBROADCAST message. Without that, I was seeing multiple repeated suspend events and resume events.

Log in to reply