代码实现全局消息钩子SetWindowsHookExA监视按键记录

简单的使用Windows提供的Hook API SetWindowsHookExA,实现弹窗提示每次按下的按键
步骤:
1.编写一个Dll调用SetWindowsHookExA,实现弹窗
2.编写一个exe调用LoadLibrary加载生成的Dll
代码实现全局消息钩子SetWindowsHookExA监视按键记录_第1张图片
dll代码如下

#include
#include
HHOOK shook;
LRESULT WINAPI keyboard(int nCode,WPARAM wParam,LPARAM lParam);
BOOL APIENTRY DllMain( HINSTANCE hModule,DWORD  ul_reason_for_call,LPVOID lpReserved )
{
	switch(ul_reason_for_call)
    {
		case DLL_PROCESS_ATTACH:
		{
			shook = SetWindowsHookExA(WH_KEYBOARD,keyboard,hModule,0);
		}
     case DLL_THREAD_ATTACH:
     case DLL_THREAD_DETACH:
     case DLL_PROCESS_DETACH:
		 break;
    }
    return TRUE;
}	
LRESULT __stdcall keyboard(int nCode,WPARAM wParam,LPARAM lParam)
{
	if(nCode >=0)
	{
		if(!(lParam & 0x80000000))
		{
			char tcKey[MAX_PATH] = {0};
			GetKeyNameTextA(lParam,tcKey,MAX_PATH);
			MessageBoxA(NULL,tcKey,tcKey,MB_OK);
			return CallNextHookEx(shook,nCode,wParam,lParam);
		}
	}
	else
		return CallNextHookEx(shook,nCode,wParam,lParam);
}

exe代码如下

#include
#include
void main()
{
	LoadLibraryA("sethook.dll");
	getchar();
}

你可能感兴趣的:(C/C++编程)