GetMonitorBrightness() 因访问冲突而崩溃

GetMonitorBrightness() crashes with Access Violation

我正在尝试设置一个小程序来根据当前房间亮度调整显示器亮度。

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

everytime I try to use GetMonitorBrightness() the program crashes with Access Violation while writing at Position 0x00000000 (I translated this error from German)

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

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

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

While trying to debug I saw that pPhysicalMonitors actually contains the monitor I want to use, but pPhysicalMonitors[0].hPhysicalMonitor contains 0x0000000 only. Could this be part of the problem?

没有。但是,您没有检查以确保 cPhysicalMonitors > 0,并且您忽略了 GetPhysicalMonitorsFromHMONITOR() 的 return 值以确保它实际上填充了 PHYSICAL_MONITOR 数组与数据。