类中的EnumDisplayMonitors回调函数

C++: EnumDisplayMonitors callback inside a class

本文关键字:回调 函数 EnumDisplayMonitors      更新时间:2023-10-16

我有一个问题与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;
}

但是当我把所有东西都转移到我的实际代码库并包含在一个类中时,它返回一个错误。我不知道我做得对不对。->下面是代码片段:

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;
}

我只是通过将回调函数更改为public来解决我的问题。