Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get main window handle from process id?

How to get main window handle from process id?

I want to bring this window to the front.

It works well in "Process Explorer".

like image 618
Alexey Malistov Avatar asked Dec 11 '09 15:12

Alexey Malistov


People also ask

How can I get process ID handle?

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.

What is main window handle?

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.

What is a handle to a process?

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.


2 Answers

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); } 
like image 130
Hiale Avatar answered Sep 20 '22 13:09

Hiale


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...

like image 36
Jerry Coffin Avatar answered Sep 23 '22 13:09

Jerry Coffin