天道酬勤 发表于 2025-3-21 15:00:57

逆向工程核心原理读书笔记 05

# 第21章 Windows消息hook

将程序定义的挂钩过程安装到挂钩链中。

```c
HHOOK SetWindowsHookExA(
int       idHook,//hook type
HOOKPROClpfn,//hook proc
HINSTANCE hmod,//hook proc的DLL句柄
DWORD   dwThreadId//与挂钩过程关联的线程的标识符。
);
```

DLL:

这里要注意`nCode>=0`

```c
#include<Windows.h>
#include<stdio.h>

#define ProcessName"notepad.exe"

HINSTANCE g_hInstance = NULL;
HHOOK g_hHook = NULL;
HWND g_hWnd = NULL;

BOOL APIENTRY DllMain( HMODULE hModule,
                     DWORDul_reason_for_call,
                     LPVOID lpReserved
                     )
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
      g_hInstance = hModule;

    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
      break;
    }
    return TRUE;
}

LRESULT CALLBACK KeyboardProc(int nCode, WPARAM wParam, LPARAM lParam)
{
    char szPath = { 0 };
    char* p = NULL;
    if (nCode>=0)
    {
      // 31bit: 0:press, 1:release
      if (!(lParam & 0x80000000))
      {
            GetModuleFileNameA(NULL, szPath, MAX_PATH);
            p = strrchr(szPath, '\\')+1;
            printf("%s", p);
            if (!_stricmp(p, ProcessName))
            {
                return 1;
            }
      }

    }
    return CallNextHookEx(g_hHook, nCode, wParam, lParam);
}

extern "C" __declspec(dllexport) void hookStart()
{
    g_hHook = SetWindowsHookEx(WH_KEYBOARD, KeyboardProc, g_hInstance, 0);
}

extern "C" __declspec(dllexport) void hookStop()
{
    UnhookWindowsHookEx(g_hHook);
    g_hHook = NULL;
}

```

c:

```c
#include<Windows.h>
#include<stdio.h>
#include <conio.h>
#define DLLName "E:\\B\\RevEngBook\\Project1\\x64\\Debug\\Dll1.dll"
const char* ProcessName = "Project1.exe";
typedef void (*PFNHookStart)();
typedef void (*PFNHookStop)();

int main()
{
        HMODULE hDLL;
        PFNHookStart HookStart = NULL;
        PFNHookStop HookStop = NULL;
        hDLL = LoadLibraryA(DLLName);
        HookStart = (PFNHookStart)GetProcAddress(hDLL, "hookStart");
        HookStop = (PFNHookStop)GetProcAddress(hDLL, "hookStop");
        HookStart();
        printf("HoookStart\n");
        while (_getch() != 'q')
                ;
        HookStop();
        FreeLibrary(hDLL);
        return 0;
}
```

mjb 发表于 2025-3-21 23:47:43

水一水。。

lihaixiang1990n 发表于 2025-3-22 06:40:07

来学习学习
页: [1]
查看完整版本: 逆向工程核心原理读书笔记 05