【问题标题】:GetMonitorBrightness() crashes with Access ViolationGetMonitorBrightness() 因访问冲突而崩溃
【发布时间】:2016-03-19 03:55:08
【问题描述】:

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

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

【问题讨论】:

    标签: c++ winapi screen-brightness


    【解决方案1】:

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

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

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

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

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

    没有。但是,您没有检查以确保 cPhysicalMonitors 大于 0,并且您忽略了 GetPhysicalMonitorsFromHMONITOR() 的返回值以确保它实际上正在用数据填充 PHYSICAL_MONITOR 数组。

    【讨论】:

    • 非常感谢,DWORD 和地址已修复。
    猜你喜欢
    • 2012-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多