user7179690
user7179690

Reputation: 1123

Get the Windows screen saver timeout using Win32 API

I want to create a simple C++ application on windows which check the display turn off time.

After some search I found this function using windows.h

int time;
bool check;
check = SystemParametersInfo(SPI_GETSCREENSAVETIMEOUT, 0, &time, 0);
if (check) {
    cout << "The Screen Saver time is : " << time << endl;
}
else {
    cout << "Sorry dude the windows api can't do it" << endl;
}

but when I use this code the time is always zero and in my windows setting i set the windows to turn off display on 5 minutes

I tried some solution my self I changed the time type to long long and I got garbage number a very big number, so what I made wrong to get the screen turn off time.

OS: Windows 10

Compiler: Mingw32 and i test with MSVC 2015

Upvotes: 4

Views: 1363

Answers (1)

rustyx
rustyx

Reputation: 85276

Screen saver timeout and display power-off timeout are two different things.

SPI_GETSCREENSAVETIMEOUT returns the screen saver timeout - the time after which the Screen Saver is activated. If a screen saver was never configured, the value is 0.

The display power-off timeout is the time after which the power to the screen is cut, and is part of the power profile (and can differ e.g. for battery vs. AC power).

Use CallNtPowerInformation to get the display power-off timeout:

#include <iostream>
#include <windows.h>
#include <powerbase.h>

#pragma comment(lib, "PowrProf.lib")

int main() {
    SYSTEM_POWER_POLICY powerPolicy;
    DWORD ret;

    ret = CallNtPowerInformation(SystemPowerPolicyCurrent, nullptr, 0, &powerPolicy, sizeof(powerPolicy));

    if (ret == ERROR_SUCCESS) {
        std::cout << "Display power-off timeout : " << powerPolicy.VideoTimeout << "s \n";
    }
    else {
        std::cerr << "Error 0x" << std::hex << ret << std::endl;
    }

}

Example output:

Display power-off timeout : 600 s

Upvotes: 6

Related Questions