ctypes 文档建议使用use_last_error=True
捕捉GetLastError()
以安全的方式。请注意,您需要在引发时检索错误代码WinError
:
from ctypes import *
SPI_SETDESKWALLPAPER = 0x0014
SPIF_SENDCHANGE = 2
SPIF_UPDATEINIFILE = 1
def errcheck(result, func, args):
if not result:
raise WinError(get_last_error())
user32 = WinDLL('user32',use_last_error=True)
SystemParametersInfo = user32.SystemParametersInfoW
SystemParametersInfo.argtypes = [c_uint,c_uint,c_void_p,c_uint]
SystemParametersInfo.restype = c_int
SystemParametersInfo.errcheck = errcheck
SystemParametersInfo(SPI_SETDESKWALLPAPER,0,r'xxx',SPIF_UPDATEINIFILE | SPIF_SENDCHANGE)
Output:
Traceback (most recent call last):
File "C:\test.py", line 17, in <module>
SystemParametersInfo(SPI_SETDESKWALLPAPER,0,r'c:\xxx',SPIF_UPDATEINIFILE | SPIF_SENDCHANGE)
File "C:\test.py", line 9, in errcheck
raise WinError(get_last_error())
FileNotFoundError: [WinError 2] The system cannot find the file specified.
所有这些工作的替代方法是使用pywin32 http://sourceforge.net/projects/pywin32/files并打电话win32gui.SystemsParametersInfo
.