I need to set time.sleep() after my start_instances() in order for every instance to be open so get_instances() works properly. But that's not "nice" since i would have to change the amount of seconds in time.sleep() depending on the amount of instances i want to open. Is there a better way?
import ctypes
from ctypes import wintypes
import subprocess
user32 = ctypes.windll.user32
def start_instances(instance_path, instance_cwd, instance_amount):
processes = []
for _ in range(instance_amount):
process = subprocess.Popen(
[(instance_path)],
cwd=instance_cwd,
)
processes.append(process)
print(f"\033[32m{processes}\033[0m")
return processes
def get_instances(instance_title):
instances = []
def enum_handler(hWnd, lParam):
# https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-iswindowvisible
if user32.IsWindowVisible(hWnd):
# https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getwindowtextlengthw
length = user32.GetWindowTextLengthW(hWnd)
buffer = ctypes.create_unicode_buffer(length + 1)
# https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getwindowtextw
user32.GetWindowTextW(hWnd, buffer, length + 1)
instances.append((hWnd, buffer.value))
return True
# https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-enumwindows
user32.EnumWindows(
ctypes.WINFUNCTYPE(ctypes.c_bool, wintypes.HWND, wintypes.LPARAM)(enum_handler), 0
)
target_instances = [
instance for instance in instances if instance_title in instance[1]
]
print(f"\033[32m{target_instances}\033[0m")
return target_instances