Qt detect when computer goes into sleep?

后端 未结 3 407
半阙折子戏
半阙折子戏 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:28

    There is no Qt way to detect when computer goes to sleep or hibernation. But there are some platform dependent ways to do it.

    On Windows you can listen for the WM_POWERBROADCAST message in your 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 executes a program with arguments. You can start a program and notify your main application in some way:

    #!/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.

提交回复
热议问题