1

My goal is to write a script in python that shows how much percent of the desktop is hidden behind all visible windows on top of it, even those not created by the script.

I wrote

import win32api, win32gui

def get_visible_area():
    # Get the dimensions of the desktop
    desktop_width = win32api.GetSystemMetrics(win32con.SM_CXVIRTUALSCREEN)
    desktop_height = win32api.GetSystemMetrics(win32con.SM_CYVIRTUALSCREEN)

    # Get the list of all open windows
    windows = win32gui.GetDesktopWindow()
    (child_windows, _) = win32gui.EnumChildWindows(windows)

    # Initialize variables to keep track of the visible area
    visible_area = desktop_width * desktop_height
    total_area = desktop_width * desktop_height

    # Iterate through all open windows and subtract their visible area from the total visible area
    for window in child_windows:
        if win32gui.IsWindowVisible(window):
            left, top, right, bottom = win32gui.GetWindowRect(window)
            window_width = right - left
            window_height = bottom - top
            window_area = window_width * window_height
            visible_area -= window_area

    # Calculate the percentage of the desktop that is hidden behind windows
    percentage_hidden = (total_area - visible_area) / total_area * 100

    return percentage_hidden

print("Percentage of desktop hidden behind windows:", get_visible_area(), "%")

But it does not take into account that windows overlap each other and it includes all windows somewhere, not only those that cover the desktop and are visible. How to include only those and have a 0-100% value.

Neo-S
  • 21
  • 3
  • You could use the [Regions](https://learn.microsoft.com/en-us/windows/win32/gdi/regions) API, though I'm not sure whether there is a clever way to calculate the final area of a region (there is a dumb way that consists of rendering the region into a bitmap, and then counting the number of pixels that were painted). – IInspectable Jan 29 '23 at 08:40
  • Why is the regions api better iyo? – Neo-S Jan 29 '23 at 09:00
  • Because anything that (potentially) produces the correct result is better than a solution that doesn't. The Regions API can be used to build a single region where areas that are occupied by more than one contributor won't get counted more than once. – IInspectable Jan 29 '23 at 09:08
  • 1
    It's not that simple (maybe a bit complex for an SO question). You can store 1 and 0 in a bitmap of desktop size and "paint" on it for each window. Or you can use this algorithm to compute the area https://gist.github.com/skeeto/3614100 with a quadtree data structure to store windows bounds and determine intersections rapidly. With python, you can use https://pypi.org/project/Pyqtree/ – Simon Mourier Jan 29 '23 at 09:36
  • @Neo-S [read this](https://stackoverflow.com/questions/65074942/total-area-of-overlapping-rectangles) – SuperUser Jan 30 '23 at 12:15

0 Answers0