I am using the following code segment to change the screen resolution of windows via python and it works fine for 1366x768, 1024x768, 800x600 resolutions. But it is not working for 1440x810 resolution. What is wrong here?
import ctypes
import struct
import sys
def set_res(width, height, bpp=32):
DM_BITSPERPEL = 0x00040000
DM_PELSWIDTH = 0x00080000
DM_PELSHEIGHT = 0x00100000
CDS_UPDATEREGISTRY = 0x00000001
SIZEOF_DEVMODE = 148
user32 = ctypes.WinDLL('user32.dll')
DevModeData = struct.calcsize("32BHH") * '\x00'
DevModeData += struct.pack("H", SIZEOF_DEVMODE)
DevModeData += struct.calcsize("H") * '\x00'
dwFields = (width and DM_PELSWIDTH or 0) | (height and DM_PELSHEIGHT or 0) | (bpp and DM_BITSPERPEL or 0)
DevModeData += struct.pack("L", dwFields)
DevModeData += struct.calcsize("l9h32BHL") * '\x00'
DevModeData += struct.pack("LLL", bpp or 0, width or 0, height or 0)
DevModeData += struct.calcsize("8L") * '\x00'
result = user32.ChangeDisplaySettingsA(DevModeData, CDS_UPDATEREGISTRY)
return result == 0 # success if zero, some failure otherwise
if(__name__ == "__main__"):
result = set_res(1440, 810)
sys.exit(result)
Checked with my system screen resolution options available.
It had below resolution options available.
The script worked fine for all the above options.
Note that 1440 x 810 resolution option is not available and hence it also didn't work on my system.
May be issue is related to support for the screen resolution on that system and not specific to the above code.
You must have the resolution supported by windows for this to work.
For those who want this script for python 3.x use this:
import ctypes
import struct
import sys
def set_res(width, height, bpp=32):
DM_BITSPERPEL = 0x00040000
DM_PELSWIDTH = 0x00080000
DM_PELSHEIGHT = 0x00100000
CDS_UPDATEREGISTRY = 0x00000001
SIZEOF_DEVMODE = 148
user32 = ctypes.WinDLL('user32.dll')
DevModeData = struct.calcsize("32BHH") * bytes('\x00','utf')
DevModeData += struct.pack("H", SIZEOF_DEVMODE)
DevModeData += struct.calcsize("H") * bytes('\x00','utf')
dwFields = (width and DM_PELSWIDTH or 0) | (height and DM_PELSHEIGHT or 0) | (bpp and DM_BITSPERPEL or 0)
DevModeData += struct.pack("L", dwFields)
DevModeData += struct.calcsize("l9h32BHL") * bytes('\x00','utf')
DevModeData += struct.pack("LLL", bpp or 0, width or 0, height or 0)
DevModeData += struct.calcsize("8L") * bytes('\x00','utf')
result = user32.ChangeDisplaySettingsA(DevModeData, CDS_UPDATEREGISTRY)
return result == 0 # success if zero, some failure otherwise
if(__name__ == "__main__"):
result = set_res(1280, 720)
sys.exit(result)
User contributions licensed under CC BY-SA 3.0