Home >Backend Development >C++ >How to Get the Main Window Handle from a Process ID in C ?

How to Get the Main Window Handle from a Process ID in C ?

DDD
DDDOriginal
2024-12-18 16:41:09399browse

How to Get the Main Window Handle from a Process ID in C  ?

How to Retrieve the Main Window Handle from a Process ID

Question:

How can you retrieve the main window handle from a given process ID? You want to bring this particular window to the forefront, and Process Explorer seems to perform this action seamlessly.

Answer:

Investigating the mechanism used by .NET to determine the main window revealed that it employs the EnumWindows() function. The following C code provides a similar implementation:

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);
}

This code iterates through all top-level windows and checks if the process ID of the window matches the desired process ID. If it does, it further verifies if the window is a main window (has no owner and is visible) and returns its handle.

The above is the detailed content of How to Get the Main Window Handle from a Process ID in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn