Question

I'm trying to intercept messages sent to a window running in another process, so that I can react to a few of them.

The injecting application is an x86 WPF application that calls this method via p/invoke. I pass the handle to a window in another x86 process.

extern "C" BOOL INJ_API ::InterceptMessages(HWND hWnd)
{
    if (!WM_MY_INJECT)
    {
        WM_MY_INJECT = RegisterWindowMessage(TEXT("WM_MY_INJECT"));
    }

    // Get the ID of the thread running the window.
    DWORD ThreadId = GetWindowThreadProcessId(hWnd, NULL);

    // Set the hook
    hhk = SetWindowsHookEx(WH_GETMESSAGE, HookProc, hinstDLL, ThreadId);

    // hhk is non-zero, so the hook is set up

    // This will block until the WM_MY_INJECT message is processed, the hook is unhooked, and we are done injecting the application.
    LRESULT result = SendMessage(hWnd, WM_MY_INJECT, NULL, NULL);

    return TRUE;
}

I know that the message is being sent, because result is the correct value. But the DLL is never loaded by the other process, and the message is called without my hook intercepting it.

Was it helpful?

Solution

WH_GETMESSAGE is for hooking messages that are retreived from a message queue by GetMessage() or PeekMessage(). Messages sent with SendMessage() do not go through those functions, and thus will not trigger a WH_GETMESSAGE hook. You need to either use PostMessage() instead of SendMessage(), or use a WH_CALLWNDPROC or WH_CALLWNDPROCRET hook instead of a WH_GETMESSAGE hook.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top