Detour作为微软官方的Hook库,其代码是非常稳定的,并且多线程安全。(当然了没有绝对的安全,日常使用够了)
Hook MessageBox 示例:
#include <iostream>
#include <windows.h>
#include "detours.h"
#pragma comment (lib,"detours.lib")
typedef int (WINAPI* MESSAGEBOXW_)(_In_opt_ HWND hWnd, _In_opt_ LPCWSTR lpText, _In_opt_ LPCWSTR lpCaption, _In_ UINT uType);
MESSAGEBOXW_ messagebox = 0;
//保存函数原型
static int (WINAPI* OLD_MessageBoxW)(HWND hWnd, LPCWSTR lpText, LPCWSTR lpCaption, UINT uType) = MessageBoxW;
int WINAPI New_MessageBoxW(HWND hWnd, LPCWSTR lpText, LPCWSTR lpCation, UINT uType) {
int ret = OLD_MessageBoxW(hWnd, L"输入的参数已修改", L"[测试]", uType);
return ret;
}
void HOOK() {
DetourRestoreAfterWith();
DetourTransactionBegin();
//更新所有线程,确保所有拦截点都能正确更新
DetourUpdateThread(GetCurrentThread());
// 这里可以连续多次调用DetourAttach,表明HOOK多个函数
// 目标函数指针的地址和指向DetourFunction函数的指针。目标函数未作为参数提供,因为它必须已经存储在目标指针中。
DetourAttach(&(PVOID&)OLD_MessageBoxW, New_MessageBoxW);
DetourTransactionCommit();
}
void UnHook()
{
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
//这里可以连续多次调用DetourDetach,表明撤销多个函数HOOK
DetourDetach(&(PVOID&)OLD_MessageBoxW, New_MessageBoxW);
DetourTransactionCommit();
}
void main()
{
::MessageBoxW(NULL, L"正常消息框", L"测试", MB_OK);
HOOK();
::MessageBoxW(NULL, L"正常消息框", L"测试", MB_OK);
UnHook();
return;
}
静态库如上,快来下载资源吧