8

我正在创建一个键盘钩子,其中 KeyboardProc 是 CWidget 类的静态成员。

class CWidget
{
   static LRESULT CALLBACK KeyboardProc(int code, WPARAM wParam, LPARAM lParam );

};

我想在 CWidget::KeyboardProc 中调用 CWidget 的非静态成员。

最好的方法是什么?

KeyboardProc 没有任何 32 位 DWORD,我可以在其中传递“this”指针。

4

1 回答 1

7

鉴于您可能一次只需要安装一个键盘挂钩,只需在您的类中添加一个静态 pThis 成员:

// Widget.h
class CWidget
{
    static HHOOK m_hHook;
    static CWidget *m_pThis;

public:
    /* NOT static */
    bool SetKeyboardHook()
    {
        m_pThis = this;
        m_hHook = ::SetWindowsHookEx(WH_KEYBOARD, StaticKeyboardProc, /* etc */);
    }

    // Trampoline
    static LRESULT CALLBACK StaticKeyboardProc(int code, WPARAM wParam, LPARAM lParam)
    {
        ASSERT(m_pThis != NULL);
        m_pThis->KeyboardProc(code, wParam, lParam);
    }

    LRESULT KeyboardProc(int code, WPARAM wParam, LPARAM lParam);

    /* etc. */
};

您需要定义静态成员:

// Widget.cpp
CWidget *CWidget::m_pThis = NULL;
于 2008-12-02T10:42:30.317 回答