Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
501 views
in Technique[技术] by (71.8m points)

c++ - EnumDisplayMonitors callback

I am trying to use the EnumDisplayMonitors to create a dynamic array of each monitor and store the DISPLAY_DEVICE structure. Why is the below code not correct?

BOOL CALLBACK MyInfoEnumProc(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {

    MONITORINFOEX iMonitor;
    iMonitor.cbSize = sizeof(MONITORINFOEX);
    GetMonitorInfo(hMonitor, &iMonitor);

    if (iMonitor.dwFlags == DISPLAY_DEVICE_MIRRORING_DRIVER)
    {
        return true;
    }
    else
    {
        *reinterpret_cast<ScreenArray*>(dwData) = ScreenArray(&iMonitor);
        return true;
    };

}

Called using

ScreenArray monitorArray[15];

int i = 0;
EnumDisplayMonitors(NULL, NULL, MyInfoEnumProc, reinterpret_cast<LPARAM>(&monitorArray[i++]));

The first in the array (monitorArray[0]) returns correct information for the second monitor but monitorArray[1] is max values.

EDIT: Solved The method I used was just implementing a function I created:

MonitorArray *mA = reinterpret_cast<MonitorArray*>(dwData);
        mA->addScreen(&iMonitor);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

EnumDisplayMonitors takes the parameter you pass it and calls your callback once for each monitor, passing it the same parameter every time. Your index into monitorArray is never incremented. Instead you need to manage the indexing within the callback itself.

Here's a little class that automatically builds a vector of all monitors in the system.

struct MonitorRects
{
    std::vector<RECT>   rcMonitors;

    static BOOL CALLBACK MonitorEnum(HMONITOR hMon,HDC hdc,LPRECT lprcMonitor,LPARAM pData)
    {
        MonitorRects* pThis = reinterpret_cast<MonitorRects*>(pData);
        pThis->rcMonitors.push_back(*lprcMonitor);
        return TRUE;
    }

    MonitorRects()
    {
        EnumDisplayMonitors(0, 0, MonitorEnum, (LPARAM)this);
    }
};

Use it like this:

MonitorRects monitors;
cout << "You have " << monitors.rcMonitors.size() << " monitors connected.";

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...