在 ctypes 中获取当前桌面壁纸

Get current desktop wallpaper in ctypes

我尝试使用 ctypes 模块在 Python 中获取当前壁纸的路径。但结果程序 returns 值 1.

import ctypes

SPI_GETDESKWALLPAPER = 0x0073

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

如果需要,请尝试此代码,也许它会对您有所帮助:)

from os import path, getenv, getcwd
from ctypes import windll
import ctypes
from shutil import copyfile
from PIL import Image
from tempfile import NamedTemporaryFile


SPI_GETDESKWALLPAPER = 0x0073

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

currentWallpaper = getenv(
            'APPDATA') + "\Microsoft\Windows\Themes\TranscodedWallpaper"   #this is path manuel 

if returnImgObj == True:
        
        a= Image.open(currentWallpaper)
        a.show()
        print(str(currentWallpaper))
        
else:
        tempFile = NamedTemporaryFile(mode="wb", suffix='.jpg').name
        copyfile(currentWallpaper, tempFile)
        a= Image.open(currentWallpaper)
        a.show()
        print(str(currentWallpaper))
    

该值是 return 在 path 中编辑的。 a 在您的示例中是 return 代码(1=成功)。定义参数类型和 return 类型也是一个好习惯,因此 ctypes 在将参数从 Python 转换为 C 时不必猜测,反之亦然。

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)