如何使用hook(非注入dll)

#include <Windows.h>
#include <iostream>

using namespace std;

HHOOK mouseHook;

LRESULT __stdcall MouseHookCallback(int nCode, WPARAM wParam, LPARAM lParam)
{
    if (nCode >= 0)
    {
        switch (wParam)
        {       
        case WM_MOUSEWHEEL:
            return 1;
        }
    }
    return CallNextHookEx(mouseHook, nCode, wParam, lParam);
}

void SetHook()
{
    if (!(mouseHook = SetWindowsHookEx(WH_MOUSE_LL, MouseHookCallback, NULL, 0)))
    {
        cout << "Failed to install mouse hook!" << endl;
    }
}

void ReleaseHook()
{
    UnhookWindowsHookEx(mouseHook);
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    SetHook();
    MSG msg;

    while (GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    return msg.wParam;
}

上面的项目是使用钩子拦截鼠标滚轮的消息

需要注意的是,这种低级挂钩只能用 类似WH_MOUSE_LL这种参数,只有在注入dll的全局钩子中才能使用WH_MOUSE参数,并且要确保SetWindowsHookEx中的第三个参数和第四个参数都为NULL,这些都是经过测试的。

posted @ 2019-10-25 14:52  strive-sun  阅读(801)  评论(0编辑  收藏  举报