detours

Detours是微軟開發的一個函式館,可用於捕獲系統API。

準備工作

在用其進行程式開發之前,得做一些準備工作。

一.下載Detours
在微軟官網上可免費下載Detours

二.安裝Detours
一路NEXT
三.生成Detours庫
在安裝後的資料夾下找不到直接可以拿來用的LIB檔案,但是卻有SRC檔案(在**\Microsoft Research\Detours Express 2.1\src下)。該資料夾下還有Makefile,可以直接用來生成庫。
將Detours路徑下的SCR資料夾拷貝到**\Microsoft Visual Studio 9.0\VC路徑下,注意是整個資料夾(其它版本VC自己照著複製)
在system32目錄找到cmd右鍵以管理員身份運行,切換至 c:\Program Files\Microsoft Visual Studio 9.0\VC\bin目錄運行vcvars32.bat
切換到\Microsoft Visual Studio9.0\VC\SRC,然後輸入..\bin\nmake指令,編譯成功後在\Microsoft Visual Studio9.0\VC\Lib檔案下就能找到detoured.lib與detours.lib檔案了。

簡單例子

HOOK MessageBoxW函式

#include "stdafx.h"

//#include "DetourHook.h"

#include

#pragma comment(lib, "detours.lib")

#pragma comment(lib, "detoured.lib")

static int (WINAPI* OLD_MessageBoxW)(HWND hWnd,LPCWSTR lpText,LPCWSTR lpCaption,UINT uType)=MessageBoxW;

int WINAPI NEW_MessageBoxW(HWND hWnd,LPCWSTR lpText,LPCWSTR lpCaption,UINT uType)

{

//修改輸入參數,調用原函式

int ret=OLD_MessageBoxW(hWnd,L"輸入參數已修改",L"[測試]",uType);

return ret;

}

VOID Hook()

{

DetourRestoreAfterWith();

DetourTransactionBegin();

DetourUpdateThread(GetCurrentThread());

//這裡可以連續多次調用DetourAttach,表明HOOK多個函式

DetourAttach(&(PVOID&)OLD_MessageBoxW,NEW_MessageBoxW);

DetourTransactionCommit();

}

VOID UnHook()

{

DetourTransactionBegin();

DetourUpdateThread(GetCurrentThread());

//這裡可以連續多次調用DetourDetach,表明撤銷多個函式HOOK

DetourDetach(&(PVOID&)OLD_MessageBoxW,NEW_MessageBoxW);

DetourTransactionCommit();

}

int APIENTRY _tWinMain(HINSTANCE hInstance,

HINSTANCE hPrevInstance,

LPTSTR lpCmdLine,

int nCmdShow)

{

MessageBoxW(0,L"正常訊息框",L"測試",0);

Hook();

MessageBoxW(0,L"正常訊息框",L"測試",0);

UnHook();

return 0;

}

1.

#include "stdafx.h"

2.

//#include "DetourHook.h"

3.

#include

4.

#pragma comment(lib, "detours.lib")

5.

#pragma comment(lib, "detoured.lib")

6.

static int (WINAPI* OLD_MessageBoxW)(HWND hWnd,LPCWSTR lpText,LPCWSTR lpCaption,UINT uType)=MessageBoxW;

7.

int WINAPI NEW_MessageBoxW(HWND hWnd,LPCWSTR lpText,LPCWSTR lpCaption,UINT uType)

8.

{

9.

//修改輸入參數,調用原函式

10.

int ret=OLD_MessageBoxW(hWnd,L"輸入參數已修改",L"[測試]",uType);

11.

return ret;

12.

}

13.

VOID Hook()

14.

{

15.

DetourRestoreAfterWith();

16.

DetourTransactionBegin();

17.

DetourUpdateThread(GetCurrentThread());

18.

//這裡可以連續多次調用DetourAttach,表明HOOK多個函式

19.

DetourAttach(&(PVOID&)OLD_MessageBoxW,NEW_MessageBoxW);

20.

DetourTransactionCommit();

21.

}

22.

VOID UnHook()

23.

{

24.

DetourTransactionBegin();

25.

DetourUpdateThread(GetCurrentThread());

26.

//這裡可以連續多次調用DetourDetach,表明撤銷多個函式HOOK

27.

DetourDetach(&(PVOID&)OLD_MessageBoxW,NEW_MessageBoxW);

28.

DetourTransactionCommit();

29.

}

30.

int APIENTRY _tWinMain(HINSTANCE hInstance,

31.

HINSTANCE hPrevInstance,

32.

LPTSTR lpCmdLine,

33.

int nCmdShow)

34.

{

35.

MessageBoxW(0,L"正常訊息框",L"測試",0);

36.

Hook();

37.

MessageBoxW(0,L"正常訊息框",L"測試",0);

38.

UnHook();

39.

return 0;

40.

}

相關詞條

熱門詞條

聯絡我們