微软Hook库初体验


1.安装

今天突然心血来潮,想随便研究些东西。网上看到这个库就下载安装了一下。

整体还算顺利

首先官网下载此库

地址是:https://www.microsoft.com/en-us/research/project/detours/?from=http%3A%2F%2Fresearch.microsoft.com%2Fsn%2Fdetours

进去之后选择download。

下载文件到本地之后目录下面有个src文件夹,还有一些简单的实例。

这里就不看了,直接进行编译。

 

我的开发环境是vs2013,编译的采用markfile编写的。用微软出的nmake编译。

首先进入vs目录下的vc目录,C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin下面有个vcvars32.bat

是设置vc编译环境变量的。通过dos先执行此批处理。

执行后切换到src目录,执行命令

>nmake

编译成功后会在父级目录生成两个文件夹,include ,obj.x86

这两个文件夹.

通过vs打开后

创建一个项目,配置项目属性 引用目录 > inlcude目录.

添加预处理 命令.

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

 

2.使用

DetourRestoreAfterWith(); //不知道什么用

DetourTransactionBegin(); //不知道什么用 
DetourUpdateThread(GetCurrentThread()); //不知道什么用 
DetourAttach(&(PVOID&)OldMessageBoxA, MyMessageBoxA); //Hook跳转实现 
error = DetourTransactionCommit(); // 错误返回.

 

下面是一个完成的代码。hook MessageBoxA

算是自己做一个备忘吧。

#include <windows.h> 
#include "detours.h" 
#include <string>

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

static int (WINAPI * OldMessageBoxA)( 
    _In_opt_ HWND hWnd, 
    _In_opt_ LPCSTR lpText, 
    _In_opt_ LPCSTR lpCaption, 
    _In_ UINT uType) = MessageBoxA;

int 
WINAPI 
MyMessageBoxA( 
_In_opt_ HWND hWnd, 
_In_opt_ LPCSTR lpText, 
_In_opt_ LPCSTR lpCaption, 
_In_ UINT uType){ 
    
     return OldMessageBoxA(NULL, "Hello Hook","hello", MB_OK); 
}

int __stdcall WinMain( 
    HINSTANCE hInstance, 
    HINSTANCE hPrevInstance, 
    LPSTR lpCmdLine, 
    int nCmdShow 
    ) 
{ 
     long error;

    MessageBoxA(NULL, "Hello wolrd!", "hello", MB_OK);

    DetourRestoreAfterWith();

    DetourTransactionBegin(); 
    DetourUpdateThread(GetCurrentThread()); 
    DetourAttach(&(PVOID&)OldMessageBoxA, MyMessageBoxA); 
    error = DetourTransactionCommit();

    if (error == NO_ERROR) { 
        OutputDebugStringA("Done"); 
    } 
    else { 
        OutputDebugStringA("Error"); 
    }

    switch (error) 
    { 
        case ERROR_INVALID_BLOCK: 
            OutputDebugStringA("ERROR_INVALID_BLOCK"); 
            break; 
        case ERROR_INVALID_HANDLE: 
            OutputDebugStringA("ERROR_INVALID_HANDLE"); 
            break; 
        case ERROR_INVALID_OPERATION: 
             OutputDebugStringA("ERROR_INVALID_OPERATION"); 
             break; 
        case ERROR_NOT_ENOUGH_MEMORY: 
            OutputDebugStringA("ERROR_NOT_ENOUGH_MEMORY"); 
            break; 
        default: 
            break; 
    }

    MessageBoxA(NULL, "Hello wolrd!", "hello", MB_OK);

    return 0; 
}

 

 

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM