Winapi c++ trying to get primary monitor's brightness

0

I tried to get the brightness of the primary monitor using the following code:

    POINT monitorPoint = { 0, 0 };
    HANDLE monitor = MonitorFromPoint(monitorPoint, MONITOR_DEFAULTTOPRIMARY);

    DWORD minb, maxb, currb;
    if (GetMonitorBrightness(monitor, &minb, &currb, &maxb) == FALSE) {
        std::cout << GetLastError() << std::endl;
    }

But it fails and GetLastError() returns 87 which means Invalid Parameter.

EDIT: I managed to solve this using EnumDisplayMonitors() and GetPhysicalMonitorsFromHMONITOR() like this:

std::vector<HANDLE> pMonitors;

BOOL CALLBACK MonitorEnumProc(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {

   DWORD npm;
   GetNumberOfPhysicalMonitorsFromHMONITOR(hMonitor, &npm);
   PHYSICAL_MONITOR *pPhysicalMonitorArray = new PHYSICAL_MONITOR[npm];

   GetPhysicalMonitorsFromHMONITOR(hMonitor, npm, pPhysicalMonitorArray);

   for (unsigned int j = 0; j < npm; ++j) {
      pMonitors.push_back(pPhysicalMonitorArray[j].hPhysicalMonitor);
   }

   delete pPhysicalMonitorArray;

   return TRUE;
}

// and later inside main simply:
EnumDisplayMonitors(NULL, NULL, MonitorEnumProc, NULL);

// and when I need to change the brightness:
for (unsigned int i = 0; i < pMonitors.size(); ++i) {
   SetMonitorBrightness(pMonitors.at(i), newValue);
}

Now I encounter 2 new problems:

1) From EnumDisplayMonitors() I get 2 monitor handles since I have 2 monitors. The problem is that only my primary works. Whenever I try to so something with the secondary monitor I get this error:

0xC0262582: ERROR_GRAPHICS_I2C_ERROR_TRANSMITTING_DATA

2) After using SetMonitorBrightness() for some time it stops working even for the primary monitor and I get the following error:

0xC026258D

c++
winapi
asked on Stack Overflow Nov 23, 2016 by DimChtz • edited Nov 23, 2016 by DimChtz

1 Answer

2

You are passing an HMONITOR to the function. However, its documentation states that a handle to a physical monitor is required instead, and suggests that you call GetPhysicalMonitorsFromHMONITOR() to obtain it. Indeed, since MonitorFromPoint() returns an HMONITOR your code would have failed to compile with STRICT enabled, a practise that helps root out such mistakes.

You should include error checking for the call to MonitorFromPoint(). And the documentation also suggests that you should call GetMonitorCapabilities() passing MC_CAPS_BRIGHTNESS to make sure the monitor supports brightness requests.

Please refer to the documentation of GetMonitorBrightness() for more detail:

answered on Stack Overflow Nov 23, 2016 by David Heffernan • edited Nov 23, 2016 by David Heffernan

User contributions licensed under CC BY-SA 3.0