How to get hwnd windows by process name. For example, I can get hwnd by the name of the window

hwnd = win32gui.FindWindow(None, "Notepad") 

Is it also easy to get hwnd by process name?

    1 answer 1

    It simply will not work, because:

    1. There may be several processes with the same name (for example, you can open several Notepad windows).
    2. A process can have multiple windows.

    Therefore, you first need to get a list of processes with the specified file name (or, for simplicity, the first process that matches this condition), then the list of windows for this process (processes).

    1. Get a list of processes that have a file name equal to notepad.exe

    You can use the package psutil

     import psutil # Список процессов с именем файла notepad.exe: notepads = [item for item in psutil.process_iter() if item.name() == 'notepad.exe'] print(notepads) # [<psutil.Process(pid=4416, name='notepad.exe') at 64362512>] # Просто pid первого попавшегося процесса с именем файла notepad.exe: pid = next(item for item in psutil.process_iter() if item.name() == 'notepad.exe').pid # (вызовет исключение StopIteration, если Блокнот не запущен) print(pid) # 4416 

    2. Get the list of process windows with the given pid

    To get a list of process windows, you can use the EnumWindows function.

    For example, you need to get all the windows of the process with ID 4416:

     import win32gui import win32process def enum_window_callback(hwnd, pid): tid, current_pid = win32process.GetWindowThreadProcessId(hwnd) if pid == current_pid and win32gui.IsWindowVisible(hwnd): windows.append(hwnd) # pid = 4416 # pid уже получен на предыдущем этапе windows = [] win32gui.EnumWindows(enum_window_callback, pid) # Выводим заголовки всех полученных окон print([win32gui.GetWindowText(item) for item in windows]) 

    Conclusion:

     ['Безымянный — Блокнот'] 

    If you open another page setting in Notepad, the list will be as follows:

     ['Параметры страницы', 'Безымянный — Блокнот'] 
    • Thanks for the help once again, but here is the task, I know only the name of the process, and it is known that the name of the process is one such as progID1242111.exe. I need to get hwnd by process name and get the window name. I can't watch the pid. Do you have a sample code for this? - Dmitry
    • @ Dmitry Mizantropovich, added the answer - insolor
    • Thanks a lot! - Dmitry