Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

winapi

pywin32

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

like image 954
steve Avatar asked Dec 18 '22 06:12

steve


1 Answers

Enumerate windows and then get the process handle for each window

You need these APIs:

  • win32gui.EnumWindows() to enumerate all top-level windows (that is no child windows aka controls)
  • win32process.GetWindowThreadProcessId() to get process ID from window handle
  • win32api.OpenProcess() to get process handle from process ID

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

You need these APIs:

  • win32process.EnumProcesses() to enumerate all processes
  • win32api.GetWindowLong() with arguent GWL_STYLE to get window styles and GWL_EXSTYLE to get extended window styles
  • win32gui.GetParent() to determine unowned windows

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][8], 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.

like image 59
zett42 Avatar answered May 03 '23 13:05

zett42