Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ hooking to a different application, how to find thread id from process id?

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.

like image 471
sjcomp Avatar asked May 07 '11 16:05

sjcomp


People also ask

Is thread ID same as process ID?

The thread ID of the initial (main) thread is the same as the process ID of the entire process. Thread IDs for subsequently created threads are distinct. They are allocated from the same numbering space as process IDs. Process IDs and thread IDs are sometimes also referred to collectively as task IDs.

How do you find the thread ID of a thread handle?

If you have a thread identifier, you can get the thread handle by calling the OpenThread function. OpenThread enables you to specify the handle's access rights and whether it can be inherited. A thread can use the GetCurrentThread function to retrieve a pseudo handle to its own thread object.

How do I find the thread ID of a process in Linux?

Identifying the thread On Unix® and Linux® systems, you can use the top command: $ top -n 1 -H -p [pid]replacing [pid] with the process ID of the affected process. On Solaris®, you can use the prstat command: $ prstat -L -p [pid]replacing [pid] with the process ID of the affected process.

What is a process thread ID?

Threads are the basic unit to which an operating system allocates processor time. A thread is code that is to be serially executed within a process and more than one thread can be executing code inside a process.


1 Answers

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);
like image 82
David Heffernan Avatar answered Oct 13 '22 16:10

David Heffernan