detours使用。

Detours库可以用来进行Api Hook,使用Detours需要一个detours.h和detours.lib文件。

简单例子Hook MessageBoxW:

C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include "stdafx.h"
#include <windows.h>
#include "detours.h"
#pragma comment (lib,"detours.lib")
int(WINAPI *OldFunc)(HWND hWnd, LPCWSTR lpText, LPCWSTR lpCaption, UINT uType) = MessageBoxW;
int WINAPI Fake_Message(HWND hWnd, LPCWSTR lpText, LPCWSTR lpCaption, UINT uType)
{
int nRet = OldFunc(hWnd, L"Fake_MessageBox", L"Fake", uType);
return nRet;
}
int Hook()
{
DetourRestoreAfterWith();
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
if (DetourAttach((PVOID*)&OldFunc, Fake_Message) != NULL)
{
OutputDebugStringA("Fake_Message DetourAttach Failed!rn");
return 0;
}
DetourTransactionCommit();
}
void UnHook()
{
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourDetach((PVOID*)&OldFunc, Fake_Message);
DetourTransactionCommit();
}
int _tmain(int argc, _TCHAR* argv[])
{
MessageBoxW(0, L"Hook Before", L"Test", 0);
Hook();
MessageBoxW(0, L"Hook", L"Test", 0);
UnHook();
return 0;
}