You are not calling the function correctly. You are passing the address of a BOOL
variable as the second parameter, but also assigning the function return value to that variable. The pfOn
parameter is not the same thing as the function return value
You need to modify the code to separate those two distinct values.
if (GetDevicePowerState(monitor,&result))
{
... do something with result
}
else
{
... the call to GetDevicePowerState failed, result is ill-defined
}
By similar token, you are not checking the return value of GetMonitorInfo
.
Now, once we fix this, the code might look like this:
#include <iostream>
#include <Windows.h>
int main(int argc, char *argv[])
{
POINT p = { 0, 0 };
HMONITOR monitor = MonitorFromPoint(p, MONITOR_DEFAULTTONULL);
if (monitor == NULL)
std::cout << "No monitor found for point (0, 0)\n";
else {
MONITORINFOEX info;
BOOL result;
if (GetDevicePowerState(monitor,&result))
{
std::cout << "Result = " << result << "\n";
if(result==TRUE){
std::cout << "Monitor is on!: \n";
}else{
std::cout << "Monitor is off!: \n";
}
}
else
{
std::cout << "Call to GetDevicePowerState failed\n";
}
if (GetMonitorInfo(monitor, &info))
{
std::cout << "Monitor: " << info.szDevice << "\n";
}
else
{
std::cout << "Call to GetMonitorInfo failed\n";
}
}
}
And when I run this program, the output is:
Call to GetDevicePowerState failed
Call to GetMonitorInfo failed
So, why does the call to GetDevicePowerState
fail? Well, because that function does not accept an HMONITOR
. It accepts a handle to a device and an HMONITOR
does not meet the requirement.
And why does the call to GetMonitorInfo
fail? Well, you failed to do what the documentation told you to do. It says:
You must set the cbSize member of the structure to sizeof(MONITORINFO) or sizeof(MONITORINFOEX) before calling the GetMonitorInfo function.