Загрузка данных


"""
Красит таскбар Windows 10 в цвет нижней кромки активного окна.
Без размытия и прозрачности (сплошной цвет).

Установка:  pip install pillow
Запуск:     python taskbar_color.py
Остановка:  Ctrl+C (таскбар вернётся к обычному виду)
"""
import ctypes
import time
from ctypes import wintypes

from PIL import ImageGrab

user32 = ctypes.windll.user32
user32.SetProcessDPIAware()

# --- настройки ---
INTERVAL = 0.05   # как часто обновлять (сек)
SMOOTH = 0.35     # плавность перехода цвета: 1 = мгновенно, меньше = плавнее
SAMPLE_PX = 6     # высота полоски, по которой берём цвет

# --- структуры для SetWindowCompositionAttribute ---
class ACCENT_POLICY(ctypes.Structure):
    _fields_ = [
        ("AccentState", ctypes.c_int),
        ("AccentFlags", ctypes.c_int),
        ("GradientColor", ctypes.c_uint),
        ("AnimationId", ctypes.c_int),
    ]


class WCA_DATA(ctypes.Structure):
    _fields_ = [
        ("Attribute", ctypes.c_int),
        ("Data", ctypes.POINTER(ACCENT_POLICY)),
        ("SizeOfData", ctypes.c_size_t),
    ]


WCA_ACCENT_POLICY = 19
ACCENT_DISABLED = 0
ACCENT_ENABLE_GRADIENT = 1  # сплошной цвет, без блюра


def set_accent(hwnd, state, r=0, g=0, b=0):
    color = (255 << 24) | (b << 16) | (g << 8) | r  # AABBGGRR, alpha = 255
    policy = ACCENT_POLICY(state, 2, color, 0)
    data = WCA_DATA(WCA_ACCENT_POLICY, ctypes.pointer(policy), ctypes.sizeof(policy))
    user32.SetWindowCompositionAttribute(hwnd, ctypes.byref(data))


def get_class(hwnd):
    buf = ctypes.create_unicode_buffer(256)
    user32.GetClassNameW(hwnd, buf, 256)
    return buf.value


def get_rect(hwnd):
    r = wintypes.RECT()
    user32.GetWindowRect(hwnd, ctypes.byref(r))
    return r.left, r.top, r.right, r.bottom


def main():
    # при автозапуске ждём, пока Windows создаст таскбар
    taskbar = 0
    while not taskbar:
        taskbar = user32.FindWindowW("Shell_TrayWnd", None)
        if not taskbar:
            time.sleep(1)

    screen_w = user32.GetSystemMetrics(0)
    screen_h = user32.GetSystemMetrics(1)
    tb_left, tb_top, tb_right, tb_bottom = get_rect(taskbar)

    current = None  # текущий цвет (float r, g, b)
    skip_classes = {"Shell_TrayWnd", "Progman", "WorkerW", "Windows.UI.Core.CoreWindow"}

    print("Работает. Ctrl+C для выхода.")
    try:
        while True:
            if not user32.IsWindow(taskbar):
                taskbar = user32.FindWindowW("Shell_TrayWnd", None)
                if not taskbar:
                    time.sleep(1)
                    continue
                tb_left, tb_top, tb_right, tb_bottom = get_rect(taskbar)

            hwnd = user32.GetForegroundWindow()
            if not hwnd or get_class(hwnd) in skip_classes or user32.IsIconic(hwnd):
                time.sleep(INTERVAL)
                continue

            left, top, right, bottom = get_rect(hwnd)
            # нижняя кромка окна, но не ниже верха таскбара
            y = min(bottom, tb_top) - 2
            y0 = max(0, y - SAMPLE_PX)
            x0 = max(0, left)
            x1 = min(screen_w, right)
            if y <= y0 or x1 - x0 < 10:
                time.sleep(INTERVAL)
                continue

            try:
                img = ImageGrab.grab(bbox=(x0, y0, x1, y)).convert("RGB")
                target = img.resize((1, 1)).getpixel((0, 0))
            except Exception:
                time.sleep(INTERVAL)
                continue

            if current is None:
                current = [float(c) for c in target]
            else:
                current = [c + (t - c) * SMOOTH for c, t in zip(current, target)]

            r, g, b = (int(round(c)) for c in current)
            set_accent(taskbar, ACCENT_ENABLE_GRADIENT, r, g, b)
            time.sleep(INTERVAL)
    except KeyboardInterrupt:
        pass
    finally:
        set_accent(taskbar, ACCENT_DISABLED)
        print("Остановлено, таскбар восстановлен.")


if __name__ == "__main__":
    main()