SetWindowHookEx crashes explorer.exe only if the same tid is get by the main window?

  c++, hook, hwnd, winapi

I am trying to set a WH_CALLWNDPROC hook on a window using the HWND I got from WindowFromPoint

When getting an HWND through the WindowFromPoint function you sometimes get one of the children’s instead of the main window.

Pretty good visualized with the Finder tool inside spy++

HWND's

So what I do is simple

wcout << "INFO: Waiting 1 second before first hwnd...n";
this_thread::sleep_for(chrono::milliseconds(1000));
HWND targetHwnd = getHwndFromMousePos(); //Gets hwnd from mouse pos with WindowFromPoint
outHwndData(targetHwnd);
DWORD targetPID;
DWORD targetTID = GetWindowThreadProcessId(targetHwnd, &targetPID);

then

hook = setHook(targetTID); //hook is the global HHOOK and setHook is a exported function in a dll
if (hook == NULL) {
    cout << "ERROR: Could not set hookn";
    return 1;
}

The function inside the dll

extern "C" __declspec(dllexport) HHOOK __stdcall setHook(DWORD targetTid) {
    return SetWindowsHookEx(WH_CALLWNDPROC, wmProcCallback, hInst, targetTid);
}

When targetHwnd is a children hwnd it works fine.

But when targetHwnd is the upper hwnd (green marked one) it crashes the window (not the entire explorer.exe)

enter image description here

The problem here is, even if the thread id is the same for both hwnds, the behaviour is different and crashes the window if the upper HWND (green marked one) is used to get the tid

The hooking is actually done. But as soon as the window receives any messages (when moving the mouse inside of the window), the window crashes.

So at last SetWindowsHookEx is called with the same parameters (tid) in both cases.
The only difference is that I get the tid from different hwnd.
Why does the behaviour differ in the first place? The HWND has nothing to do with the hooking process but it works in one way. I am just ultra confused…

Anyway, I hope you guys understand. Any tips are appreciated. Please don’t roast me, I already roasted myself.

Source: Windows Questions C++

LEAVE A COMMENT