6

I would like to add a hook to an application. I am using SetWindowsHookEx and I can create a system wide hook, but I want to create a hook for a particular application. I need to have thread id of the target application to hook it. I know title of the window, I know exe name and from these I can get window handle and process id, but how do I get the thread id? I saw a post about how to do it in c#, but I do not see how to get a list of threads in c++.

HWND windowHandle = FindWindow(NULL, _T("SomeOtherApp"));
DWORD processId = GetWindowThreadProcessId(windowHandle, NULL);
DWORD threadId = ??? // How do I get thread id here?
HHOOK hook = ::SetWindowsHookEx( WH_CBT, HookCBTProc, hInst, threadId);

Thanks, Alexander.

Community
  • 1
  • 1
sjcomp
  • 177
  • 2
  • 9

2 Answers2

4

GetWindowThreadProcessId() returns the thread ID. You are erroneously assigning the thread ID to the process ID variable. Instead write:

HWND windowHandle = FindWindow(NULL, _T("SomeOtherApp"));
DWORD threadId = GetWindowThreadProcessId(windowHandle, NULL);
HHOOK hook = ::SetWindowsHookEx(WH_CBT, HookCBTProc, hInst, threadId);
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
2

The answer is GetWindowThreadProcessId. It takes the window handle and returns the ID of the thread that created the window and optionally the process ID.

Marius Bancila
  • 16,053
  • 9
  • 49
  • 91