如何设置Windows 10桌面背景的平滑过渡?

时间:2019-07-10 15:21:27

标签: python python-3.x windows windows-10

我正在使用以下代码更改Windows桌面背景

ctypes.windll.user32.SystemParametersInfoW(20, 0, "C:/image/jkk7LGN03aY.jpg" , 0)

我的image目录中有很多图片,我将这些图片一一设置如下

for path in image_list:
    ctypes.windll.user32.SystemParametersInfoW(20, 0, path , 0)
    time.sleep(5)

桌面背景图像正在突然变化,但是我想要一个平滑的过渡。我该怎么办?

1 个答案:

答案 0 :(得分:3)

这是我经常使用的纯Python代码段:

它使用pywin32启用活动桌面并使用平滑过渡设置墙纸(确保您未禁用窗口效果或看不到任何淡入淡出效果)

import ctypes
from typing import List

import pythoncom
import pywintypes
import win32gui
from win32com.shell import shell, shellcon

user32 = ctypes.windll.user32


def _make_filter(class_name: str, title: str):
    """https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-enumwindows"""

    def enum_windows(handle: int, h_list: list):
        if not (class_name or title):
            h_list.append(handle)
        if class_name and class_name not in win32gui.GetClassName(handle):
            return True  # continue enumeration
        if title and title not in win32gui.GetWindowText(handle):
            return True  # continue enumeration
        h_list.append(handle)

    return enum_windows


def find_window_handles(parent: int = None, window_class: str = None, title: str = None) -> List[int]:
    cb = _make_filter(window_class, title)
    try:
        handle_list = []
        if parent:
            win32gui.EnumChildWindows(parent, cb, handle_list)
        else:
            win32gui.EnumWindows(cb, handle_list)
        return handle_list
    except pywintypes.error:
        return []


def force_refresh():
    user32.UpdatePerUserSystemParameters(1)


def enable_activedesktop():
    """https://stackoverflow.com/a/16351170"""
    try:
        progman = find_window_handles(window_class='Progman')[0]
        cryptic_params = (0x52c, 0, 0, 0, 500, None)
        user32.SendMessageTimeoutW(progman, *cryptic_params)
    except IndexError as e:
        raise WindowsError('Cannot enable Active Desktop') from e


def set_wallpaper(image_path: str, use_activedesktop: bool = True):
    if use_activedesktop:
        enable_activedesktop()
    pythoncom.CoInitialize()
    iad = pythoncom.CoCreateInstance(shell.CLSID_ActiveDesktop,
                                     None,
                                     pythoncom.CLSCTX_INPROC_SERVER,
                                     shell.IID_IActiveDesktop)
    iad.SetWallpaper(str(image_path), 0)
    iad.ApplyChanges(shellcon.AD_APPLY_ALL)
    force_refresh()


if __name__ == '__main__':
    set_wallpaper(r'D:\Wallpapers\Cool\enchanted_mountain_4k.jpg')