【问题标题】:C++: EnumDisplayMonitors callback inside a classC++:类中的 EnumDisplayMonitors 回调
【发布时间】:2026-01-14 08:25:02
【问题描述】:

EnumDisplayMonitors 回调有问题。我想获得每个屏幕的数量和屏幕分辨率。看来它正在使用此代码。

#include <windows.h>
#include <iostream>
#include <vector>

#pragma comment(lib, "user32.lib") 

std::vector< std::vector<int> > screenVector;
int screenCounter = 0;

BOOL CALLBACK MonitorEnumProcCallback(  _In_  HMONITOR hMonitor,
                                        _In_  HDC hdcMonitor,
                                        _In_  LPRECT lprcMonitor,
                                        _In_  LPARAM dwData ) {
    screenCounter++;

    MONITORINFO  info;
    info.cbSize =  sizeof(MONITORINFO);

    BOOL monitorInfo = GetMonitorInfo(hMonitor,&info);

    if( monitorInfo ) {
        std::vector<int> currentScreenVector;
        currentScreenVector.push_back( screenCounter );
        currentScreenVector.push_back( abs(info.rcMonitor.left - info.rcMonitor.right) );
        currentScreenVector.push_back( abs(info.rcMonitor.top - info.rcMonitor.bottom) );
        std::cout   << "Monitor " 
                    << currentScreenVector.at(0) 
                    << " -> x: "
                    << currentScreenVector.at(1)  
                    << " y: "
                    << currentScreenVector.at(2) 
                    << "\n";    
    }

    return TRUE;
}

int main() {
    BOOL b = EnumDisplayMonitors(NULL,NULL,MonitorEnumProcCallback,0);
    system("PAUSE");
    return 0;
}

但是当我将所有内容转移到我的实际代码库并包含在一个类中时,它会返回一个错误。我不知道我这样做是否正确。 -> 这是sn-p:

ScreenManager::ScreenManager() {
   BOOL monitorInitialized = EnumDisplayMonitors( NULL, NULL, MonitorEnumProc, reinterpret_cast<LPARAM>(this) );
}

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

    reinterpret_cast<ScreenManager*>(dwData)->callback(hMonitor,hdcMonitor,lprcMonitor);
    return true;
}

bool ScreenManager::callback(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor){

    screenCounter++;

    MONITORINFO  info;
    info.cbSize =  sizeof(MONITORINFO);

    BOOL monitorInfo = GetMonitorInfo(hMonitor,&info);

    if( monitorInfo ) {
        std::vector<int> currentScreenVector;
        currentScreenVector.push_back( screenCounter );
        currentScreenVector.push_back( abs(info.rcMonitor.left - info.rcMonitor.right) );
        currentScreenVector.push_back( abs(info.rcMonitor.top - info.rcMonitor.bottom) );

    }

    return true;
}

【问题讨论】:

    标签: c++ winapi screen monitor


    【解决方案1】:

    我刚刚通过将回调函数更改为 public 解决了我的问题。

    【讨论】:

    • 更好:只需将静态枚举函数集成到类中即可。比你的班级回电被允许是私人的!