挂钩到其他线程时,SetWindowsHookEx返回NULL

时间:2017-07-12 09:35:36

标签: c++ winapi

当我调用SetWindowsHookEx(WH_GETMESSAGE,MYHOOKPROC,hin,threadId)时,

钩子代码在dll中;如果threadid param是一个threadid,则此函数返回0,GetLastError返回87,如果threadid为0,则返回正常值。

[injection.dll]

LRESULT CALLBACK MYHOOKPROC(int code, WPARAM w, LPARAM l);

void load_hook(DWORD threadId) {
    HINSTANCE hin = ::GetModuleHandle(TEXT("InjectionHook.dll"));
    HHOOK hook = ::SetWindowsHookEx(WH_GETMESSAGE, MYHOOKPROC, hin, threadId);
    DWORD k = GetLastError();
    if (hook != NULL) {
        MessageBox(NULL, TEXT("HOOKING"), TEXT(""), MB_OKCANCEL | MB_ICONERROR);
    }

}

LRESULT CALLBACK MYHOOKPROC(int code, WPARAM w, LPARAM l) {
    MSG* pMsg = (MSG*)l;
    if (WM_NULL == pMsg->message) {

    }
    return CallNextHookEx(NULL, code, w, l);
}

injection.def

LIBRARY InjectionHook

EXPORTS
load_hook
MYHOOKPROC

主要功能:

#include "stdafx.h"
#include <Windows.h>

typedef void(*load_hook)(DWORD);

int main()
{
    HWND hwnd;
    hwnd = ::FindWindow(TEXT("Progman"), NULL);
    DWORD threadId;
    ::GetWindowThreadProcessId(hwnd, &threadId);
    HINSTANCE hi = LoadLibrary(TEXT("../../InjectionHook/Debug/InjectionHook.dll"));
    load_hook lh = (load_hook)GetProcAddress(hi, "load_hook");
    lh(threadId);

    SendMessage(hwnd, WM_NULL, 0, 0);
    return 0;
}

1 个答案:

答案 0 :(得分:2)

您正在传递进程ID作为线程ID!

请改为尝试:

DWORD threadId, pid;
threadId = ::GetWindowThreadProcessId(hwnd, &pid);