问题
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.
回答1:
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);
回答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.
来源:https://stackoverflow.com/questions/5922248/c-hooking-to-a-different-application-how-to-find-thread-id-from-process-id