Search code examples
winapipywin32

pywin32: how to get window handle from process handle and vice versa


Two use-cases:

  1. Enumerate windows and then get the process handle for each window

  2. Enumerate processes and then get the main application window handle for each process


Solution

  • Enumerate windows and then get the process handle for each window

    You need these APIs:

    Enumerate processes and then get the main application window handle for each process

    You need these APIs:

    By filtering the result of EnumWindows() using GetWindowThreadProcessId() you can get all windows that belong to a given process.

    Determining the main window can be tricky as there is no single window style that would designate a window as the main window. After all, an application might have multiple main windows.

    Best you could do is to use the same rules that the taskbar uses to determine application windows, because that's what the user perceives as main windows:

    The Shell places a button on the taskbar whenever an application creates an unowned window—that is, a window that does not have a parent and that has the appropriate extended style bits.

    To ensure that the window button is placed on the taskbar, create an unowned window with the WS_EX_APPWINDOW extended style. To prevent the window button from being placed on the taskbar, create the unowned window with the WS_EX_TOOLWINDOW extended style. As an alternative, you can create a hidden window and make this hidden window the owner of your visible window.

    Use GetParent() and GetWindowLong() to determine the unowned windows that have the right window styles according to these rules.