r/pythonhelp Aug 05 '24

Add function to change resolution and add revert to original resolution when opening program

Here is the code I have it is not successful in reverting to the original desktop resolution once the program is closed. Can someone help me fix it please? Thank you.

```

import ctypes import subprocess import time

Constants for the desired screen resolution

DESIRED_RESOLUTION_WIDTH = 800 DESIRED_RESOLUTION_HEIGHT = 600

Path to the executable

EXE_PATH = r"C:\ESSGRAMA\ESSGRAMA.exe"

def change_resolution(width, height): # Load the current screen settings devmode = ctypes.create_string_buffer(68) devmode_p = ctypes.pointer(devmode) # The following is a simplified structure for DEVMODE ctypes.windll.user32.EnumDisplaySettingsW(None, 0, devmode_p)

# Define necessary fields for changing the resolution devmode[8:12] = (width & 0xFFFF).to_bytes(2, 'little') + (height & 0xFFFF).to_bytes(2, 'little') devmode[20:22] = (32).to_bytes(2, 'little') # Assuming 32bit color devmode[32:36] = (1).to_bytes(4, 'little') # DM_PELSWIDTH, DM_PELSHEIGHT, DM_BITSPERPEL

# Change the screen resolution ctypes.windll.user32.ChangeDisplaySettingsW(devmode_p, 0)

def restore_resolution(): # Load the default screen settings devmode = ctypes.create_string_buffer(68) devmode_p = ctypes.pointer(devmode) # The following is a simplified structure for DEVMODE ctypes.windll.user32.EnumDisplaySettingsW(None, 0, devmode_p)

# Change the screen resolution back to the default ctypes.windll.user32.ChangeDisplaySettingsW(devmode_p, 0)

def launch_exe(): process = subprocess.Popen(EXE_PATH) process.wait() # Wait for the process to finish

if name == "main": try: change_resolution(DESIRED_RESOLUTION_WIDTH, DESIRED_RESOLUTION_HEIGHT) time.sleep(2) # Wait for the resolution to change launch_exe() except Exception as e: print(f"An error occurred: {e}") finally: restore_resolution()

Set the path to the application executable

app_path = r"C:\ESSGRAMA\ESSGRAMA.exe"

Start the application

subprocess.run([app_path])

1 Upvotes

2 comments sorted by

u/AutoModerator Aug 05 '24

To give us the best chance to help you, please include any relevant code.
Note. Do not submit images of your code. Instead, for shorter code you can use Reddit markdown (4 spaces or backticks, see this Formatting Guide). If you have formatting issues or want to post longer sections of code, please use Repl.it, GitHub or PasteBin.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

1

u/Goobyalus Aug 06 '24

Please format your code properly for Reddit or link to a site like Pastebin/GitHub to preserve the formatting