如何从回调方法访问自定义 class 成员

How to access the custom class members from a call back method

我想通过回调方法访问自定义 class 的成员。

我正在通过回调函数访问 m_displayImg->bIsPressAndHold = true;

它给出错误 "Identifier M_displayImg is undefined"。

class CDisplayImage
{
public:
    CDisplayImage(void);
    virtual ~CDisplayImage(void);

    int Initialize(HWND hWnd, CDC* dc, IUnknown* controller);
    void Uninitialize(int context);
    BOOL bIsPressAndHold = false;
    //code omitted
};


VOID CALLBACK DoCircuitHighlighting(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime)
{
    m_displayImg->bIsPressAndHold = true;       
   // I have omitted code for simplicity.
}

如何访问该自定义 class 成员?

之前我遇到过类似的问题。我用命名空间变量解决了它,因为 CALLBACK 函数不能接受更多的参数,你甚至不能在 lambda 捕获列表中放任何东西。

我的代码示例(内容不同,但思路是一样的):

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

namespace MonitorInfo {
    // namespace variable
    extern std::vector<MONITORINFOEX> data = std::vector<MONITORINFOEX>();

    // callback function
    BOOL CALLBACK callbackFunction(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
        MONITORINFOEX monitorInfo;
        monitorInfo.cbSize = sizeof(monitorInfo);
        GetMonitorInfo(hMonitor, &monitorInfo);
        data.push_back(monitorInfo);
        return true;
    }

    // get all monitors data
    std::vector<MONITORINFOEX> get(){
        data.clear();
        EnumDisplayMonitors(NULL, NULL, callbackFunction, 0);
        return data;
    }
};

int main(){
    auto info = MonitorInfo::get();
    printf("%d", info.size());
    return 0;
}