16,472
社区成员
发帖
与我相关
我的任务
分享
// Test3.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <windows.h>
#include <imagehlp.h>
#include <iostream>
using namespace std;
#pragma comment(lib, "ImageHlp")
//HOOK API
void SetHook();
//代理函数
//如果把 __stdcall 去掉 改成下面形式就会出错
//void MyMessage(HWND hWnd , LPCSTR lpText, LPCSTR lpCaption, UINT uType);
void __stdcall MyMessage(HWND hWnd , LPCSTR lpText, LPCSTR lpCaption, UINT uType);
HMODULE g_hMod;
int main(int argc, char* argv[])
{
//应用程序句柄
g_hMod = GetModuleHandle(NULL);
//调用系统的函数MessageBox
MessageBox(NULL, "Hello World!", "", MB_OK);
//HOOK API
SetHook();
//再次调用MessageBox
MessageBox(NULL, "Hello World!", "", MB_OK);
system("pause");
return 0;
}
//代理函数,去掉__stdcall,就出现错误
//void MyMessage(HWND hWnd , LPCSTR lpText, LPCSTR lpCaption, UINT uType)
void __stdcall MyMessage(HWND hWnd , LPCSTR lpText, LPCSTR lpCaption, UINT uType)
{
printf("Hello World!\n");
}
void SetHook()
{
//得到导入表的头指针
IMAGE_IMPORT_DESCRIPTOR* pImportDes ;
DWORD dwSize;
pImportDes = (IMAGE_IMPORT_DESCRIPTOR*)ImageDirectoryEntryToData(g_hMod,
TRUE,
IMAGE_DIRECTORY_ENTRY_IMPORT,
&dwSize);
//得到模块 USER32.dll
while (pImportDes->FirstThunk)
{
//得到模块名称
char* pszDllName = (char*)((BYTE*)g_hMod + pImportDes->Name);
if (strcmp(pszDllName, "USER32.dll") == 0)
{
break;
}
pImportDes++;
}
//在USER32.dll模块中,找到函数MessageBoxA
IMAGE_THUNK_DATA* pThunk = (IMAGE_THUNK_DATA*)((BYTE*)g_hMod + pImportDes->OriginalFirstThunk);
while (pThunk->u1.Function)
{
//函数名
char* pszFuncName = (char*)((BYTE*)g_hMod + (DWORD)pThunk->u1.AddressOfData + 2);
if (strcmp(pszFuncName, "MessageBoxA") == 0)
{
break;
}
pThunk++;
}
//修改导入地址表, 使导入地址表中MessageBoxA的地址指向代理函数的地址
DWORD* pszFuncAddr = (DWORD*)((BYTE*)g_hMod + pImportDes->FirstThunk );
DWORD* MyFuncAddr = (DWORD*)MyMessage;
WriteProcessMemory(GetCurrentProcess(), pszFuncAddr, &MyFuncAddr, sizeof(DWORD), NULL);
}