我想设置一个全局钩子,我在从我创建的dll中获取钩子过程的地址时遇到问题。
我已经在stackoverflow上读到这个问题可能是由名称错误造成的。为了消除这个问题,你必须使用extern "C"
将导出函数包装在未来的dll中,我这样做了。但是,这没有帮助。
这是我的计划:
Main.cpp的
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
HHOOK hHookKeyboard;
HINSTANCE keyboardProcDLL;
HOOKPROC hookProcKeyboard;
keyboardProcDLL = LoadLibrary(L"C:/PV_KeyboardDLL.dll");
if (keyboardProcDLL == NULL)
{
MessageBox(NULL, L"Could not load library!", L"Error", MB_ICONERROR);
return -1;
}
hookProcKeyboard = (HOOKPROC)GetProcAddress(keyboardProcDLL, "PV_KeyboardProc");
if (hHookKeyboard == NULL)
{
MessageBox(NULL, L"Could not load function from library!", L"Error", MB_ICONERROR);
return -1;
}
hHookKeyboard = SetWindowsHookEx(WH_KEYBOARD_LL, hookProcKeyboard, keyboardProcDLL, 0);
while (1)
{
}
return 0;
}
PV_KeyboardDLL.cpp
bool toggleOnOff = false; // off by default
template<typename Type>
inline bool highOrderBit(Type value)
{
return (value & (1 << sizeof(Type) * 8 - 1));
}
template<typename Type>
inline bool lowOrderBit(Type value)
{
return (value & 1);
}
extern "C"
{
__declspec(dllexport) LRESULT CALLBACK PV_KeyboardProc(int nCode, WPARAM wParam, LPARAM lParam)
{
// process event
if (nCode < 0) // do not process message
{
return CallNextHookEx(NULL, nCode, wParam, lParam);
}
if (wParam != WM_KEYDOWN)
{
return CallNextHookEx(NULL, nCode, wParam, lParam);
}
KBDLLHOOKSTRUCT* KeyBoardHookStruct = reinterpret_cast<KBDLLHOOKSTRUCT*>(lParam);
DWORD keyCode = KeyBoardHookStruct->vkCode;
bool ctrlDown, altDown;
// high-order is 1 - DOWN
ctrlDown = highOrderBit(GetKeyState(VK_LCONTROL));
altDown = highOrderBit(GetKeyState(VK_MENU));
// ctrl + alt + 1(key down)
if (ctrlDown && altDown && (keyCode == 0x31))
{
// toggle bool
MessageBox(NULL, L"Workin", L"Ok", MB_OK);
toggleOnOff = !toggleOnOff;
}
return CallNextHookEx(NULL, nCode, wParam, lParam);
}
__declspec(dllexport) bool onOrOff()
{
return toggleOnOff;
}
}
我可以加载dll,但在致电GetProcAddress()
后,hookProcKeyboard
为NULL
。
我是WINAPI的新手,我有点卡住,所以非常感谢帮助,谢谢。
答案 0 :(得分:1)
在这里看起来像一个小的(但很重要!)拼写错误:
hookProcKeyboard = (HOOKPROC)GetProcAddress(keyboardProcDLL, "PV_KeyboardProc");
if (hHookKeyboard == NULL)
{
MessageBox(NULL, L"Could not load function from library!", L"Error", MB_ICONERROR);
return -1;
}
您正在调用GetProcAddress
()来填充hookProcKeyboard
,然后检查hHookKeyboard
的值。 hookProcKeyboard
肯定是NULL
!
解决这个问题,你应该更接近解决问题......