开发者

C++ finding the GUI thread from a list of thread IDs

I am building an application program in C++ which uses Windows hooks to control third-party program开发者_JAVA技巧s. The program I am making is a tutorial program to show how to use these third-party programs. I can find the process ID of the third-party program that I want to hook into and I can then query this process ID to find a list of thread IDs to use as a parameter for the Windows API function SetWindowsHookEx. However I am concerned that from the list of thread IDs from the running process I will hook into a thread that could potentially finish at any moment. Ideally I would like to hook into the thread running the main gui which is more than likely going to be one of the longest living threads (and even if it isn't the longest living thread the tutorial program is designed to work with the GUI so it is still ideal). If the third-party application has more than one gui then I would like to find the thread ID for the main GUI.

So my question is from the list of thread IDs I get from querying the process id is there a way to find either the main GUI id or another suitable thread which will be active until the program has quit? Obviously the thread ID that I choose needs to have an event queue so I can hook into it.


How about finding the main window of the app, and then using GetWindowThreadProcessId to get the thread ID of that?

If you don't already know the main window, can try finding it using FindWindow() if you know the window name and classname, or EnumWindows() to enumerate over all the top-level windows on the desktop, and check if they belong to the target process (again using GetWindowThreadProcessId, and compare against your process ID).

The main window is usually one with a WS_CAPTION style bit(s) set. Should also check that the window is visible (IsWindowVisible) to avoid hidden worker windows (which often belong to worker threads). Can also check for WS_POPUP and the WS_EX_TOOLWINDOW styles to filter out top-level floating and dialog windows - though they are usually owned by the main GUI thread anyway.

An application can have as many 'main windows' and GUI threads as it wants; typically there's only one - but there's nothing to stop a developer from creating multiple threads, each with their own main top-level window and message loop. If you need to handle this case, your best bet might be to hook all threads that appear to own interactive UI.


The easiest and most reliable way to determine, whether a thread is a GUI thread is to call GetGUIThreadInfo:

If the specified thread does not [...] have an input queue, the function will fail.

Among others, having an input queue differentiates a GUI thread from a regular thread.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜