ApiHook类

// 头文件
// ApiHook.h: interface for the CApiHook class.
//
//////////////////////////////////////////////////////////////////////

#ifndef API_HOOK_H
#define API_HOOK_H

class CApiHook 
{
public:
    HANDLE hProc;
    Unlock();
    Lock();
    BOOL Initialize(LPCTSTR lpLibFileName, LPCTSTR lpProcName, FARPROC lpNewFunc);
    void SetHookOn(void);
    void SetHookOff(void);
    CApiHook();
    virtual ~CApiHook();

protected:
    BYTE m_OldFunc[8];
    BYTE m_NewFunc[8];
    FARPROC m_lpHookFunc;
    CRITICAL_SECTION m_cs;
};

#endif

// 实现文件
// ApiHook.cpp: implementation of the CApiHook class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "ApiHook.h"
#include

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

#define OPEN_FLAGS ( PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE )

CApiHook::CApiHook()
{
    InitializeCriticalSection(&m_cs);
}

CApiHook::~CApiHook()
{
    CloseHandle(hProc);
    DeleteCriticalSection(&m_cs);
}

void CApiHook::SetHookOn(void)
{
    DWORD dwOldFlag;

    if(WriteProcessMemory(hProc,m_lpHookFunc,m_NewFunc,5,0))
    {
        return;
    }

    MessageBox(NULL,"SetHookOn","fail",MB_OK);
    return;
}

void CApiHook::SetHookOff(void)
{
    DWORD dwOldFlag;

    if(WriteProcessMemory(hProc,m_lpHookFunc,m_OldFunc,5,0))
    {
        return;
    }
    MessageBox(NULL,"SetHookOff","fail",MB_OK);
    return;
}

BOOL CApiHook::Initialize(LPCTSTR lpLibFileName, LPCTSTR lpProcName, FARPROC lpNewFunc)
{
    HMODULE hModule;

    hModule=LoadLibrary(lpLibFileName);
    if(NULL==hModule)
        return FALSE;

    m_lpHookFunc=GetProcAddress(hModule,lpProcName);
    if(NULL==m_lpHookFunc)
        return FALSE;

    DWORD dwProcessID=GetCurrentProcessId();
    DWORD dwOldFlag;
    hProc=GetCurrentProcess(/*OPEN_FLAGS,0,dwProcessID*/);

    if(hProc==NULL)
    {
        MessageBox(NULL,"Initialize.OpenProcess","fail",MB_OK);
        return FALSE;
    }

    if(ReadProcessMemory(hProc,m_lpHookFunc,m_OldFunc,5,0))
    {
        m_NewFunc[0]=0xe9;
        DWORD*pNewFuncAddress;
        pNewFuncAddress=(DWORD*)&m_NewFunc[1];
        *pNewFuncAddress=(DWORD)lpNewFunc-(DWORD)m_lpHookFunc-5;

        return TRUE;
    }

    MessageBox(NULL,"Initialize","fail",MB_OK);
    return FALSE;
}

CApiHook::Lock()
{
    EnterCriticalSection(&m_cs);
}

CApiHook::Unlock()
{
    LeaveCriticalSection(&m_cs);
}

 

你可能感兴趣的:(ApiHook类)