【问题标题】:How to access the custom class members from a call back method如何从回调方法访问自定义类成员
【发布时间】:2017-01-24 05:44:22
【问题描述】:

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

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

它给出错误“标识符 M_displayImg 未定义”。

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

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

【问题讨论】:

  • 首先,请参阅Minimal, Complete, Verifiable Example。其次:在不使用全局变量的情况下将参数(例如关联类)滑入 Windows 回调的典型方法是 put them in the HWND's GWL_USERDATA field
  • @HostileFork 先生,我已经修改了问题。
  • code you added 并不是特别相关,因为它不显示包含m_displayImgm_startPoint 的类。大概是您希望与 HWND 关联的 那个 类。无论该类是什么,您都可以将其指针保存在 HWND 的 GWL_USERDATA 中(当它创建或传入其 HWND 时),然后在调用时从 DoCircuitHighlighting 的 hwnd 参数中提取指针。
  • @HostileFork 基本上,DoCircuitHighlighting 正在对另一个名为“CDjVuControlCtrl”的类的对象执行一些操作。为了简单起见,我省略了。
  • 如果你想要你可以申请的代码,你必须给一个合适的 MCVE。否则我只能说你遇到的机械问题是普通的 C 函数不是成员函数——它们没有“this”指针。而且您不能传递成员函数or a std::function wrapping a class and a member function together 并在需要普通C 回调的地方使用它。您需要一个全局变量来访问相关类,或者需要一种从 hwnd 获取它的方法——我已经链接了你如何做。

标签: c++ class visual-studio-2013 callback djvu


【解决方案1】:

以前我遇到过类似的问题。我用命名空间变量解决了这个问题,因为 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;
}

【讨论】:

    猜你喜欢
    • 2017-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-06
    • 2020-06-24
    • 2013-10-08
    • 1970-01-01
    相关资源
    最近更新 更多