Jairo Contreras Jairo Contreras - 1 month ago 13
Python Question

SPI_SETDESKWALLPAPER not working with tempfile.NamedTemporaryFile()

Code:

import urllib.request
import tempfile
import shutil
import ctypes

SPI_SETDESKWALLPAPER = 20
with urllib.request.urlopen('https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png') as response, tempfile.NamedTemporaryFile() as f:
shutil.copyfileobj(response, f)
ctypes.windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, f.name, 0)


However, if you use
tempfile.NamedTemporaryFile(delete=False)
it works.

The docs state:


If delete is true (the default), the file is deleted as soon as it is
closed.


In my original code the file isn't deleted until after having exited the body of the
with
statement when it is automatically closed. So why isn't
SPI_SETDESKWALLPAPER
working?

Answer

I figured out the problem:

To begin with, the value of the fWinIni parameter needs to be changed:

SPIF_UPDATEINIFILE = 0x01
SPIF_SENDCHANGE = 0x02
ctypes.windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, f.name, SPIF_UPDATEINIFILE | SPIF_SENDCHANGE)

This preserves the wallpaper after logging off.

Second, the temp file needs to be closed in order for SystemParametersInfoW to work. Therefore, delete=False is necessary.

Finally, delete the temp file manually using os.remove(f.name).

Comments