title: Invalid Monitor Handle Error When Executing SetMonitorBrightness Function In Windows - C++
body: <p>I am writing a program in Windows and I want to get the brightness of a computer monitor. I am using the Windows GetMonitorBrightness function, however I am having some trouble.</p>
  
  <p>this is my code so far:</p>
  
  <pre><code>DWORD dw;
  HMONITOR hMonitor = NULL;
  DWORD cPhysicalMonitors;
  LPPHYSICAL_MONITOR pPhysicalMonitors = NULL;
  
  LPDWORD pdwMinimumBrightness=NULL;
  LPDWORD pdwCurrentBrightness=NULL;
  LPDWORD pdwMaximumBrightness=NULL;
  
  HWND hwnd = FindWindow(NULL, NULL);
  
  hMonitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONULL);
  
  BOOL bSuccess = GetNumberOfPhysicalMonitorsFromHMONITOR(hMonitor, &amp;cPhysicalMonitors);
  pPhysicalMonitors = (LPPHYSICAL_MONITOR)malloc(cPhysicalMonitors* sizeof(PHYSICAL_MONITOR));
  bSuccess = GetPhysicalMonitorsFromHMONITOR(hMonitor, cPhysicalMonitors, pPhysicalMonitors);
  bSuccess = GetMonitorBrightness(hMonitor, pdwMinimumBrightness, pdwCurrentBrightness, pdwMaximumBrightness);
  </code></pre>
  
  <p>I wrote this following the documentation at <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/dd692972%28v=vs.85%29.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/windows/desktop/dd692972%28v=vs.85%29.aspx</a></p>
  
  <p>but when I run this code I get an error saying "This function failed because an invalid monitor handle was passed to it".</p>
  
  <p>I can't see anything wrong with the code I wrote, but I cannot seem to figure out the reason for this error.</p>
  
  <p><strong>EDIT:</strong> I should mention I am trying this out on a CRT monitor</p>
  
  <p><strong>EDIT 2:</strong> Fixed this problem, turns out I wasn't passing a proper handle to GetMonitorBrightness.</p>
  
  <pre><code>bSuccess = GetPhysicalMonitorsFromHMONITOR(hMonitor, cPhysicalMonitors, pPhysicalMonitors);
  HANDLE pmh = pPhysicalMonitors[0].hPhysicalMonitor; //&lt;---------------  
  bSuccess = GetMonitorBrightness(pmh, pdwMinimumBrightness, pdwCurrentBrightness, pdwMaximumBrightness);
  </code></pre>
  
  <p>Adding the marked line above, solved this problem</p>