Search code examples
c++classvisual-studio-2013callbackdjvu

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


I want to access the members of a custom class from callback method.

I am accessing m_displayImg->bIsPressAndHold = true; from call back functions.

i.e.

It gives error "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.
}

How can I access that custom class member?


Solution

  • Previously i encountered a similar problem. I solved it with namespaced variable, because CALLBACK function cannot accept more parameters, you cannot even put anything in lambda capture list.

    My code sample (different content, but the idea remains the same):

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