在Windows - C ++中执行SetMonitorBrightness函数时无效的监视器句柄错误

时间:2013-01-08 11:48:33

标签: c++ windows winapi

我正在Windows中编写程序,我希望获得计算机显示器的亮度。我正在使用Windows GetMonitorBrightness函数,但是我遇到了一些麻烦。

到目前为止,这是我的代码:

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, &cPhysicalMonitors);
pPhysicalMonitors = (LPPHYSICAL_MONITOR)malloc(cPhysicalMonitors* sizeof(PHYSICAL_MONITOR));
bSuccess = GetPhysicalMonitorsFromHMONITOR(hMonitor, cPhysicalMonitors, pPhysicalMonitors);
bSuccess = GetMonitorBrightness(hMonitor, pdwMinimumBrightness, pdwCurrentBrightness, pdwMaximumBrightness);

我是在http://msdn.microsoft.com/en-us/library/windows/desktop/dd692972%28v=vs.85%29.aspx

的文档后面写的

但是当我运行此代码时,我收到一条错误消息“此函数失败,因为传递给它的监视器句柄无效”。

我看不出我写的代码有什么问题,但我似乎无法弄清楚这个错误的原因。

编辑:我应该提一下我在CRT显示器上尝试这个

编辑2:修正了这个问题,事实证明我没有将正确的句柄传递给GetMonitorBrightness。

bSuccess = GetPhysicalMonitorsFromHMONITOR(hMonitor, cPhysicalMonitors, pPhysicalMonitors);
HANDLE pmh = pPhysicalMonitors[0].hPhysicalMonitor; //<---------------  
bSuccess = GetMonitorBrightness(pmh, pdwMinimumBrightness, pdwCurrentBrightness, pdwMaximumBrightness);

添加上面标记的行,解决了这个问题

2 个答案:

答案 0 :(得分:0)

您没有检查MonitorFromWindow的返回值。如果找不到监视器,它将返回NULL,因为您已通过MONITOR_DEFAULTTONULL。 Null不是监视器句柄。

尝试MONITOR_DEFAULTTONEARESTMONITOR_DEFAULTTOPRIMARY

答案 1 :(得分:0)

#pragma comment(lib,"Dxva2.lib")旁边添加#include file