Search code examples
pythonpython-3.xwindowswinapictypes

Get current desktop wallpaper in ctypes


I try to get path to current wallpaper in Python using ctypes module. But as a result program returns value 1.

import ctypes

SPI_GETDESKWALLPAPER = 0x0073

path = ctypes.create_unicode_buffer(260)
a = ctypes.windll.user32.SystemParametersInfoW(SPI_GETDESKWALLPAPER, 100, path, 0)
print(a)

Solution

  • The value is returned in path. a in your example is the return code (1=success). It's also a good habit to define the argument types and return type so ctypes doesn't have to guess when converting parameters from Python to C and vice versa.

    import ctypes as ct
    from ctypes import wintypes as w
    
    SPI_GETDESKWALLPAPER = 0x0073
    
    dll = ct.WinDLL('user32')
    dll.SystemParametersInfoW.argtypes = w.UINT,w.UINT,w.LPVOID,w.UINT
    dll.SystemParametersInfoW.restype = w.BOOL
    
    path = ct.create_unicode_buffer(260)
    result = dll.SystemParametersInfoW(SPI_GETDESKWALLPAPER, ct.sizeof(path), path, 0)
    print(result, path.value)