windows钩子初级问题

初学windows钩子遇到了问题,前来请教

问题概述:想监视按键,但按下键盘后调用不到DLL里的回调函数。

下面是钩子用到的DLL的源码:

#include <objbase.h>
#include <iostream>
using namespace std;

extern "C" __declspec(dllexport) LRESULT CALLBACK KeyboardProc(int nCode, WPARAM wParam, LPARAM lParam)
{
	cout << "KeyboardProc() is involked!" << endl;

	return CallNextHookEx(0, nCode, wParam, lParam);
}

BOOL APIENTRY DllMain(HANDLE hModel, DWORD dwReason, void* lpReserved)
{
	switch (dwReason)
	{
		case DLL_PROCESS_ATTACH:
			cout << "dll is attached!" << endl;
			break;
		case DLL_PROCESS_DETACH:
			cout << "dll is detached!" << endl;
			break;
		default:
			break;
	}

	return true;
}

下面是主程序的源码:

#include <windows.h>
#include <iostream>
using namespace std;

void main()
{
	HINSTANCE hInst = LoadLibrary("testdll.dll");

	if (NULL == hInst)
	{
		return;
	}

	HOOKPROC hkprcSysMsg = (HOOKPROC)GetProcAddress(hInst, "_KeyboardProc@12");
	cout << "hkprcSysMsg = " << hkprcSysMsg << endl;

	static HHOOK hhookSysMsg = SetWindowsHookEx(WH_KEYBOARD, hkprcSysMsg, hInst, 0);
	cout << "hhookSysMsg = " << hhookSysMsg << endl;

	Sleep(5000);

	UnhookWindowsHookEx(hhookSysMsg);
}

注:DLL中KeyboardProc的函数名是_KeyboardProc@12,我用dumpbin看过了。运行时hkprcSysMsg和hhookSysMsg都不是0。

现在的问题是运行起来后我按键调不到函数KeyboardProc(即打印不出"KeyboardProc() is involked!"这句话)。

请指点,谢谢。

阅读 4.4k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进