BOOL SetHook(HMODULE hMod);
FARPROC g_orgProc;
int WINAPI MyMessageBoxA(HWND hWnd, LPCSTR lpText, LPCSTR lpCation, UINT uType)
{
return ((PFNMESSAGEBOX)g_orgProc)(hWnd, "新函数", "HookDemo", uType);
}
int main()
{
HMODULE hMod = LoadLibrary("user32.dll");
g_orgProc = GetProcAddress(hMod, "MessageBoxA");
MessageBox(NULL, "原函数", "HookDemo", 0);
SetHook(GetModuleHandle(NULL));
MessageBox(NULL, "原函数", "HookDemo", 0);
return 0;
}
BOOL SetHook(HMODULE hMod)
{
IMAGE_DOS_HEADER* pDosHeader = (IMAGE_DOS_HEADER*)hMod;
IMAGE_OPTIONAL_HEADER* pOptHeader =
(IMAGE_OPTIONAL_HEADER*)((BYTE*)hMod + pDosHeader->e_lfanew + 24);
IMAGE_IMPORT_DESCRIPTOR* pImportDesc = (IMAGE_IMPORT_DESCRIPTOR*)
((BYTE*)hMod + pOptHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress);
while (pImportDesc->FirstThunk)
{
char* pszDllName = (char*)((BYTE*)hMod + pImportDesc->Name);
if (lstrcmpiA(pszDllName, "user32.dll") == 0) {
break;
}
pImportDesc++;
}
if (pImportDesc->FirstThunk) {
IMAGE_THUNK_DATA* pThunk = (IMAGE_THUNK_DATA*)
((BYTE*)hMod + pImportDesc->FirstThunk);
while (pThunk->u1.Function)
{
DWORD* lpAddr = (DWORD*) & (pThunk->u1.Function);
if (*lpAddr == (DWORD)g_orgProc) {
DWORD* lpNewProc = (DWORD*)MyMessageBoxA;
auto oldAddr = &MessageBoxA;
auto odw = (DWORD)oldAddr;
DWORD* oldDword= (DWORD*) & odw;
DWORD dwOldProtect;
MEMORY_BASIC_INFORMATION mbi;
//VirtualQuery(lpAddr, &mbi, sizeof(mbi));
VirtualProtect(lpAddr, sizeof(DWORD), PAGE_READWRITE, &dwOldProtect);
//WriteProcessMemory(GetCurrentProcess(), lpAddr, &lpNewProc, sizeof(DWORD), NULL);
*lpAddr = (DWORD)MyMessageBoxA;
VirtualProtect(lpAddr, sizeof(DWORD), dwOldProtect, &dwOldProtect);
return TRUE;
}
}
pThunk++;
}
return FALSE;
}