【问题标题】:SetWindowsHookEx, KeyboardProc and Non-static membersSetWindowsHookEx、KeyboardProc 和非静态成员
【发布时间】:2008-12-02 10:30:32
【问题描述】:

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

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

};

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

最好的方法是什么?

KeyboardProc 没有任何可以传递“this”指针的 32 位 DWORD。

【问题讨论】:

    标签: c++ windows hook


    【解决方案1】:

    鉴于您可能一次只需要安装一个键盘挂钩,只需将静态 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;
    

    【讨论】:

    • 现在我必须将我的类的所有成员设置为静态才能在方法中使用它们。你有什么想法不要发生这种情况吗?
    • 这就是m_pThis->KeyboardProc 位所做的——蹦床进入非静态上下文。这意味着只有静态的KeyboardProc 需要是静态的。
    • 这对我不起作用:unresolved external symbols: "private: static class keylogger* keylogger::this_"。在你设置m_pThis = this的那一行。
    • 您仍然需要在某处定义静态成员。
    猜你喜欢
    • 2012-10-20
    • 1970-01-01
    • 2014-04-14
    • 2012-04-13
    • 1970-01-01
    • 2012-12-04
    • 1970-01-01
    • 2016-05-20
    • 2013-11-14
    相关资源
    最近更新 更多