1. 程式人生 > >鍵盤鉤子函式注入dll

鍵盤鉤子函式注入dll

// dllmain.cpp : 定義 DLL 應用程式的入口點。
#include "stdafx.h"
#include "stdio.h"
#include "windows.h"

HINSTANCE g_hInstance=NULL;
HHOOK g_hHook = NULL;
HWND g_hwnd = NULL;


#define DEF_PROCESS_NAME "www.exe"


BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
					 )
{
	switch (ul_reason_for_call)
	{
	case DLL_PROCESS_ATTACH:
		g_hInstance = hModule;
		break;
	case DLL_THREAD_ATTACH:
	case DLL_THREAD_DETACH:
	case DLL_PROCESS_DETACH:
		break;
	}
	return TRUE;
}

LRESULT CALLBACK KeyboardProc(int nCode, WPARAM wParam, LPARAM lParam)
{
	char szPath[MAX_PATH] = {0};
	char *p = NULL;

	if (nCode == 0)
	{
		if (!(lParam & 0x80000000))
		{
			printf("dll =%ld\n", lParam);
			GetModuleFileName(NULL, szPath, MAX_PATH);
			p = strrchr(szPath, '\\');
			printf("filename = %d\n", szPath);
			if (!_stricmp(p+1, DEF_PROCESS_NAME))
			{
				return 1;
			}
		}
	}

	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


// hook.cpp : 定義控制檯應用程式的入口點。
//


#include "stdafx.h"
#include "stdio.h"
#include "windows.h"
#include "conio.h"


#define DEF_DLL_NAME "dll.dll"
#define DEF_HOOKSTART "HookStart"
#define DEF_HOOKSTOP "HookStop"


typedef void (*PFN_HOOKSTART)();
typedef void (*PFN_HOOKSTOP)();


int _tmain(int argc, _TCHAR* argv[])
{
HMODULE hDll = NULL;
PFN_HOOKSTART startHook= NULL;
PFN_HOOKSTOP stopHook= NULL;
char ch=0;


hDll = LoadLibraryA(DEF_DLL_NAME);


startHook = (PFN_HOOKSTART)GetProcAddress(hDll, DEF_HOOKSTART);
stopHook = (PFN_HOOKSTART)GetProcAddress(hDll, DEF_HOOKSTOP);


startHook();
printf("press q to quit!\n");


TEMP:
char x = getch();


if (x!= 'q')
{
goto TEMP;
}


//while(_getch()!='q');
//stopHook();


FreeLibrary(hDll);


return 0;
}