简体   繁体   中英

SetWindowsHookEx return NULL when hooking to other thread

hook code is in a dll when i call SetWindowsHookEx(WH_GETMESSAGE, MYHOOKPROC, hin, threadId); if the threadid param is an threadid this function return 0, and GetLastError return 87, if threadid is 0 ,it return a normal value.

[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

main function:

#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;
}

You are passing in a process id as the thread id!

Try this instead:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM