我已经构建了一个工作键盘记录器,现在我想将它移动到类,所以我可以随时重复使用它,甚至可以在c#等不同语言上使用它但是我遇到错误,因为相同的代码在类中不起作用。
LRESULT CALLBACK KeyboardProc(int nCode, WPARAM wParam, LPARAM lParam);
void main()
{
HINSTANCE h_instance = GetModuleHandle(NULL);
SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardProc, h_instance, 0); // Works here
}
LRESULT CALLBACK KeyboardProc(int nCode, WPARAM wParam, LPARAM lParam)
{
// Populate typedChars
return NULL;
}
class KeyboardHook
{
stringstream typedChars;
LRESULT CALLBACK KeyboardProc(int nCode, WPARAM wParam, LPARAM lParam)
{
// Populate typedChars
return NULL;
}
KeyboardHook()
{
HINSTANCE h_instance = GetModuleHandle(NULL);
SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardProc, h_instance, 0); // Does not work
}
public:
std::string Get()
{
return typedChars.str();
}
void Clear()
{
typedChars.str(std::string());
typedChars.clear();
}
};
C3867: 'KeyboardHook::KeyboardProc': function call missing argument list; use '&KeyboardHook::KeyboardProc' to create a pointer to member
所以我将其修改为SetWindowsHookEx(WH_KEYBOARD_LL, &KeyboardProc, h_instance, 0);
,现在发生了不同的错误
C2276: '&' : illegal operation on bound member function expression
我也试过但没有成功:
SetWindowsHookEx(WH_KEYBOARD_LL, (LRESULT)&KeyboardProc, h_instance, 0);
SetWindowsHookEx(WH_KEYBOARD_LL, (LRESULT)KeyboardProc, h_instance, 0);
SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardHook::KeyboardProc, h_instance, 0);
SetWindowsHookEx(WH_KEYBOARD_LL, &KeyboardHook::KeyboardProc, h_instance, 0);
答案 0 :(得分:1)
假设SetWindowsHookEx
应该使用函数指针(我永远无法理解horrible Windows API documentation),您需要将指向成员函数的指针绑定到应该调用它的对象上。如果要将其绑定到this
指向的对象(即您当时正在创建的KeyboardHook
对象),请尝试以下操作:
using std::placeholders;
SetWindowsHookEx(WH_KEYBOARD_LL,
std::bind(&KeyboardHook::KeyboardProc, this, _1, _2, _3),
h_instance, 0);
或者,KeyboardProc
可以声明为静态成员函数,但这意味着它将无法使用typedChars
成员。
答案 1 :(得分:0)
您必须将KeyboardProc
定义为静态成员
static LRESULT CALLBACK KeyboardProc(int nCode, WPARAM wParam, LPARAM lParam)
{
...
}
如果必须,可以在没有对象的情况下调用。