Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt detect when computer goes into sleep?

Tags:

c++

sleep

qt

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 connection. Basically we got a simple chat application where we want to take the user off-line.

like image 587
user3490755 Avatar asked Apr 29 '14 19:04

user3490755


People also ask

How do I know if my computer is sleeping?

Luckily, both Windows and OS X have an easy method for finding out what the problem is. For Windows: Go to Start > Programs > Accessories, right-click on Command Prompt, and open it as an administrator. Then type: It'll let you know if anything is keeping the computer awake.

Why won't my computer go to sleep?

A lot of things can keep your computer from going to sleep, like downloading a file, opening a file on the network, or even a disconnected printer with an open job. Luckily, both Windows and OS X have an easy method for finding out what the problem is.

What keeps your computer from going to sleep?

A lot of things can keep your computer from going to sleep, like downloading a file, opening a file on the network, or even a disconnected printer with an open job.


1 Answers

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.

like image 154
Nejat Avatar answered Sep 20 '22 08:09

Nejat