import logging
import time

import win32gui
import win32con


def get_window_info(hwnd):
    """获取窗口的详细信息"""
    class_name = win32gui.GetClassName(hwnd)
    window_text = win32gui.GetWindowText(hwnd)
    style = win32gui.GetWindowLong(hwnd, win32con.GWL_STYLE)

    # 检查窗口是否可见
    is_visible = win32gui.IsWindowVisible(hwnd)

    # 获取窗口位置和大小
    try:
        rect = win32gui.GetWindowRect(hwnd)
        left, top, right, bottom = rect
        width = right - left
        height = bottom - top
    except:
        width, height = 0, 0

    return {
        'hwnd': hwnd,
        'class_name': class_name,
        'title': window_text,
        'visible': is_visible,
        'width': width,
        'height': height,
        'style': style
    }


def enum_all_windows():
    """枚举所有窗口"""
    windows = []

    def callback(hwnd, windows_list):
        windows_list.append(get_window_info(hwnd))
        return True

    win32gui.EnumWindows(callback, windows)
    return windows


# 获取并打印所有窗口信息
logging.basicConfig(format='%(asctime)s %(message)s', filename='test.txt')
while True:
    time.sleep(5)
    all_windows = enum_all_windows()
    for window in all_windows:
        if window['visible']:  # 只显示可见窗口
            logging.error(f"类名: {window['class_name']:30} 标题: {window['title']:50} "
                          f"尺寸: {window['width']}x{window['height']}")
    logging.error('=====================\n\n\n')
