2016-03-18 162 views
1

我试图设置一个小程序来调整当前房间亮度的显示器亮度。GetMonitorBrightness()与访问冲突崩溃

我跟着从MSDN的指示,成立了这一点:

cout << "Legen Sie das Fenster bitte auf den zu steuernden Monitor.\n"; 
system("PAUSE"); 
HMONITOR hMon = NULL; 
char OldConsoleTitle[1024]; 
char NewConsoleTitle[1024]; 
GetConsoleTitle(OldConsoleTitle, 1024); 
SetConsoleTitle("CMDWindow7355608"); 
Sleep(40); 
HWND hWnd = FindWindow(NULL, "CMDWindow7355608"); 
SetConsoleTitle(OldConsoleTitle); 
hMon = MonitorFromWindow(hWnd, MONITOR_DEFAULTTOPRIMARY); 


DWORD cPhysicalMonitors; 
LPPHYSICAL_MONITOR pPhysicalMonitors = NULL; 
BOOL bSuccess = GetNumberOfPhysicalMonitorsFromHMONITOR(
    hMon, 
    &cPhysicalMonitors 
    ); 

if(bSuccess) 
{ 
    pPhysicalMonitors = (LPPHYSICAL_MONITOR)malloc(
     cPhysicalMonitors* sizeof(PHYSICAL_MONITOR)); 

    if(pPhysicalMonitors!=NULL) 
    { 
     LPDWORD min = NULL, max = NULL, current = NULL; 
     GetPhysicalMonitorsFromHMONITOR(hMon, cPhysicalMonitors, pPhysicalMonitors); 

     HANDLE pmh = pPhysicalMonitors[0].hPhysicalMonitor; 

     if(!GetMonitorBrightness(pmh, min, current, max)) 
     { 
      cout << "Fehler: " << GetLastError() << endl; 
      system("PAUSE"); 
      return 0; 
     } 

     //cout << "Minimum: " << min << endl << "Aktuell: " << current << endl << "Maximum: " << max << endl; 

     system("PAUSE"); 
    } 

} 

但问题:每次我尝试使用GetMonitorBrightness()程序崩溃与Access Violation while writing at Position 0x00000000(我翻译了德国这个错误)

在尝试调试时,我看到pPhysicalMonitors实际上包含我想要使用的显示器,但pPhysicalMonitors[0].hPhysicalMonitor仅包含0x0000000。这可能是问题的一部分吗?

回答

2

每次我尝试使用GetMonitorBrightness()程序与访问冲突崩溃,而在位置00000000写作(我翻译了德国这个错误)

你传递NULL指针GetMonitorBrightness(),所以它崩溃当试图将其输出值写入无效内存时。

就像GetNumberOfPhysicalMonitorsFromHMONITOR()GetMonitorBrightness()希望你通过实际变量的地址,例如:

DWORD min, max, current; 
if (!GetMonitorBrightness(pmh, &min, &current, &max)) 

虽然试图调试我看到pPhysicalMonitors实际上包含我想使用的显示器,但pPhysicalMonitors [ 0] .hPhysicalMonitor只包含0x0000000。这可能是问题的一部分吗?

号但是,你不检查,以确保cPhysicalMonitors> 0,而你忽略的GetPhysicalMonitorsFromHMONITOR()返回值,以确保它实际上是填充PHYSICAL_MONITOR阵列数据。

+0

非常感谢,DWORD和地址修复了它。 – DoktorMerlin