How to get main window handle from process id?
I want to bring this window to the front.
It works well in "Process Explorer".
If you have a process identifier, you can get the process handle by calling the OpenProcess function. OpenProcess enables you to specify the handle's access rights and whether it can be inherited. A process can use the GetCurrentProcess function to retrieve a pseudo handle to its own process object.
The MainWindowHandle property is a value that uniquely identifies the window that is associated with the process. A process has a main window associated with it only if the process has a graphical interface. If the associated process does not have a main window, the MainWindowHandle value is zero.
A process handle is an integer value that identifies a process to Windows. The Win32 API calls them a HANDLE; handles to windows are called HWND and handles to modules HMODULE. Threads inside processes have a thread handle, and files and other resources (such as registry keys) have handles also.
I checked how .NET determines the main window.
My finding showed that it also uses EnumWindows()
.
This code should do it similarly to the .NET way:
struct handle_data { unsigned long process_id; HWND window_handle; }; HWND find_main_window(unsigned long process_id) { handle_data data; data.process_id = process_id; data.window_handle = 0; EnumWindows(enum_windows_callback, (LPARAM)&data); return data.window_handle; } BOOL CALLBACK enum_windows_callback(HWND handle, LPARAM lParam) { handle_data& data = *(handle_data*)lParam; unsigned long process_id = 0; GetWindowThreadProcessId(handle, &process_id); if (data.process_id != process_id || !is_main_window(handle)) return TRUE; data.window_handle = handle; return FALSE; } BOOL is_main_window(HWND handle) { return GetWindow(handle, GW_OWNER) == (HWND)0 && IsWindowVisible(handle); }
I don't believe Windows (as opposed to .NET) provides a direct way to get that.
The only way I know of is to enumerate all the top level windows with EnumWindows()
and then find what process each belongs to GetWindowThreadProcessID()
. This sounds indirect and inefficient, but it's not as bad as you might expect -- in a typical case, you might have a dozen top level windows to walk through...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With