GetMonitorBrightness()因访问冲突而崩溃

时间:2016-03-18 19:37:34

标签: c++ winapi screen-brightness

我试图设置一个小程序来调整当前房间亮度的显示器亮度。

我按照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。这可能是问题的一部分吗?

1 个答案:

答案 0 :(得分:2)

  

每当我尝试使用GetMonitorBrightness()时,程序在写入位置0x00000000时会因访问冲突而崩溃(我从德语翻译此错误)

您正在将NULL指针传递给GetMonitorBrightness(),因此在尝试将其输出值写入无效内存时会崩溃。

就像GetNumberOfPhysicalMonitorsFromHMONITOR()一样,GetMonitorBrightness()希望您传递实际变量的地址,例如:

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

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

没有。但是,您没有检查以确保cPhysicalMonitors是&gt; 0,您忽略GetPhysicalMonitorsFromHMONITOR()的返回值,以确保它实际上用数据填充PHYSICAL_MONITOR数组。

相关问题