C/C++ code// dllmain.cpp : 定义 DLL 应用程序的入口点。
#include "stdafx.h"
#include
#include "Hook.h"
#include
static HHOOK hkb=NULL;
HINSTANCE hins; //钩子函数所在模块的句柄
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
installhook();
break;
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
//第一个参数指定钩子的类型,因为我们只用到键盘操作所以设定为WH_KEYBOARD;
//第二个参数将钩子函数的入口地址指定为KeyboardProc,当钩子钩到任何消息后便调用这个函数,即当不管系统的哪个窗口有键盘输入马上会引起KeyboardProc的动作;
//第三个参数是钩子函数所在模块的句柄;
//最后一个参数是钩子相关函数的ID用以指定想让钩子去钩哪个线程,为0时则拦截整个系统的消息;
BOOL installhook()
{
printf("install hook\n");
hkb=SetWindowsHookEx(WH_KEYBOARD,(HOOKPROC)KeyboardProc,hins,0);
if (hkb = NULL)
{
printf("set windows hook failed!\n");
}
else
{
printf("set windows hook ok!\n");
}
return TRUE;
}
LRESULT CALLBACK KeyboardProc(int nCode,WPARAM wParam,LPARAM lParam)
{
printf("process has been executed\n");
if(((DWORD)lParam&0x40000000) && (HC_ACTION==nCode))
{
printf("%c has been pressed!\n", wParam);
switch(wParam) //键盘按键标识
{
case 'G':
MessageBox(NULL, TEXT("g has been pressed!"), TEXT("message"), MB_OK);
break; //当数字键1被按下
}
}
LRESULT RetVal = CallNextHookEx( hkb, nCode, wParam, lParam );
return RetVal;
}