pywin32:如何从进程句柄获取 window 句柄,反之亦然

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

两个用例:

  1. 枚举windows然后获取每个window

  2. 的进程句柄
  3. 枚举进程然后获取每个进程的主应用window句柄

Enumerate windows and then get the process handle for each window

您需要这些 API:

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

您需要这些 API:

通过使用 GetWindowThreadProcessId() 过滤 EnumWindows() 的结果,您可以获得属于给定进程的所有 windows。

确定 main window 可能会很棘手,因为没有单一的 window 样式可以将 window 指定为 主要window。毕竟,一个应用程序可能有 multiple main windows.

您最好使用与 taskbar uses to determine application windows 相同的规则,因为这是用户认为的 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.

使用GetParent()GetWindowLong()根据这些规则确定拥有正确window样式的无主windows。