pythonwindowspyautoguiminimize

I want to hide all the running windows using python


I'm creating this program only for windows. I want an effect like win+d. I want an application that when i open it, it will hide(minimize) all windows and show the desktop. I used pygetwindow library but i can't filter the core windows. I have 3 windows open but when i get the windows using the function it returns around 15. So I couldn't make just a loop and minimize all windows.

import time
import pygetwindow as gw

def hide():
    windows = gw.getAllWindows()
    for window in windows:
        if not window.is_system:
            window.minimize()
    time.sleep(3)
    return True

print(hide())
print(gw.getAllTitles())

Here is my code. The getAllTitles function return like Windows Program Manager, Cortana, or even empty names. Also I don't want to use pyautogui to just click 'win+d'. Thank you for your help :)


Solution

  • You can use ctypes to retrive the windows title and hwnd that are not part of the system and use them with Win32Window class from pygetwindow.

    import ctypes
    from ctypes import wintypes
    import pygetwindow as pgw
    
    # Define necessary WinAPI structures and constants
    user32 = ctypes.windll.user32
    kernel32 = ctypes.windll.kernel32
    
    EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, wintypes.HWND, wintypes.LPARAM)
    GetWindowTextLength = user32.GetWindowTextLengthW
    GetWindowText = user32.GetWindowTextW
    IsWindowVisible = user32.IsWindowVisible
    EnumWindows = user32.EnumWindows
    
    # Buffer length for window title
    nChars = 256
    
    # List to store the results
    windows = []
    
    # Function to enumerate windows
    def enum_windows_proc(hwnd, lParam):
        if IsWindowVisible(hwnd):
            length = GetWindowTextLength(hwnd)
            if length > 0:
                buff = ctypes.create_unicode_buffer(nChars)
                GetWindowText(hwnd, buff, nChars)
                windows.append((hwnd, buff.value))
        return True
    
    def get_windows_list():
        EnumWindows(EnumWindowsProc(enum_windows_proc), 0)
        return windows
    
    def minimize_all():
        window_list = get_windows_list()
        for hwnd, title in window_list:
            # Use the provided hwnd
            window = pgw.Win32Window(hwnd)
            window.minimize()
    
    if __name__ == "__main__":
        minimize_all()