Context: on my office PC there is apllied corporate policy -> standard company picture on desktop wallpaper. Picture is too bright; I switch it off to more dark backgroubd color, do it by manually running the script several times per day.
Aim: automate this operation with Python
- once per some time
- check some desktop background pixel
- if it color is not equal to my preference
- then apply this color to desktop background
I have an issue with p. 2. I found following code for picking up pixel color on desktop:
def get_pixel_colour(i_x, i_y): import win32gui # pip install pywin32 #i_desktop_window_id = win32gui.GetDesktopWindow() i_desktop_window_id = win32gui.FindWindow('SysListView32', None) i_desktop_window_dc = win32gui.GetWindowDC(i_desktop_window_id) long_colour = win32gui.GetPixel(i_desktop_window_dc, i_x, i_y) i_colour = int(long_colour) win32gui.ReleaseDC(i_desktop_window_id, i_desktop_window_dc) return (i_colour & 0xff), ((i_colour >> 8) & 0xff), ((i_colour >> 16) & 0xff) print(get_pixel_colour(100, 5))
It works. At the same time it picks up color from the foreground window: if there is some app window over pixel(100, 5) then color will be grabbed from this window, not from desktop background.
Any ideas how to get desktop background color even then there is some other app is not top ?
Advertisement
Answer
Grabbing a pixel value directly from what is displayed on the screen will be a problematic solution for a script running in the background. Instead I’d try to get the actual value of the wallpaper image pixel. You can get the path to currently set wallpaper using SystemParametersInfoA
.
import ctypes SPI_SETDESKWALLPAPER = 0x14 SPI_GETDESKWALLPAPER = 0x73 buf_size = 200 path = ctypes.create_string_buffer(buf_size) ctypes.windll.user32.SystemParametersInfoA(SPI_GETDESKWALLPAPER, buf_size, path , buf_size) print(path.value)
With this path you can load the actual image, check its brightness or whatever value you are interested in, and edit according to your wishes. You could use SPI_SETDESKWALLPAPER
then to set the background to edited image or whatever else you want.