它是最小化的Windows x86/x64的API钩子库,github地址。
它能够重写目标函数。以下是最常用的一个实例,在此是以VS2013 Release Win32的格式编译它,需先编译好MinHook VC12的工程,得到libMinHook.x86.lib,再连接到此工程中:
// test.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <Windows.h>
#include "MinHook.h"
#if defined _M_X64
#pragma comment(lib, "libMinHook.x64.lib")
#elif defined _M_IX86
#pragma comment(lib, "libMinHook.x86.lib")
#endif
typedef int (WINAPI *MESSAGEBOXW)(HWND, LPCWSTR, LPCWSTR, UINT);
// Pointer for calling original MessageBoxW.
MESSAGEBOXW fpMessageBoxW = NULL;
// Detour function which overrides MessageBoxW.(绕道函数改写MessageBoxW函数)
int WINAPI DetourMessageBoxW(HWND hWnd, LPCWSTR lpText, LPCWSTR lpCaption, UINT uType)
{
return fpMessageBoxW(hWnd, L"Hooked!", lpCaption, uType);
}
int main()
{
// Initialize MinHook.
if (MH_Initialize() != MH_OK)
{
return 1;
}
// Create a hook for MessageBoxW, in disabled state.
if (MH_CreateHook(&MessageBoxW, &DetourMessageBoxW,
reinterpret_cast<void**>(&fpMessageBoxW)) != MH_OK)
{
return 1;
}
// Enable the hook for MessageBoxW.
if (MH_EnableHook(&MessageBoxW) != MH_OK)
{
return 1;
}
// Expected to tell "Hooked!".
MessageBoxW(NULL, L"Not hooked...", L"MinHook Sample", MB_OK);
// Disable the hook for MessageBoxW.
if (MH_DisableHook(&MessageBoxW) != MH_OK)
{
return 1;
}
// Expected to tell "Not hooked...".
MessageBoxW(NULL, L"Not hooked...", L"MinHook Sample", MB_OK);
// Uninitialize MinHook.
if (MH_Uninitialize() != MH_OK)
{
return 1;
}
return 0;
}
MH_Initialize是起到初始化库的作用,若不初始化,将无法使用hook API。
MH_CreateHook的作用是将MessageBoxW替换为DetourMessageBoxW,同时将真正的MessageBoxW函数地址保存到fpMessageBoxW中。此函数仅仅是创建了一个hook item,该item中保存了hook时所需要的信息,原始codes,trampline信息等。若需要使该hook生效,还需要对它进行MH_EnableHook。
MH_EnableHook:它将JMP指令写到目标函数MessageBoxW上,让其跳转到自定义设置的DetourMessageBoxW函数上。
MH_DisableHook:使hook失效,将目标函数地址原始的指令写回,但是也不删除之前用CreateHook创建的hook item。
最后的输出如下:
trampoline函数等其他参考网址