Search code examples
pythonpyautogui

Python code to close all open application in windows


I am working on pyautogui for locateonscreen but I need to make sure I have a clean windows prior to running it.

I need help with a code that will kill/close all open/active windows application and then open a single exe using subprocess.


Solution

  • you can use the psutil library to close all open/active windows applications and then open a single exe using the subprocess module:

    import psutil
    import subprocess
    
    # Kill all open/active processes
    for proc in psutil.process_iter():
        proc.kill()
    
    # Open a single exe using subprocess
    subprocess.Popen("C:\\path\\to\\exe.exe")
    

    Note that the psutil.process_iter() returns a list of all running processes on the system, and proc.kill() method is used to kill each process. The subprocess.Popen method is used to open the exe file. Make sure that you provide the correct path to the exe file. Please be aware that this script will close all open applications, including any unsaved work in progress. You should use it with caution, or for testing purpose only.

    you can instead reduce all open windows. this is safer!

    import win32gui
    import win32con
    import subprocess
    
    def minimize_all():
        def callback(hwnd, hwnds):
            if win32gui.IsWindowVisible(hwnd) and win32gui.IsWindowEnabled(hwnd):
                hwnds.append(hwnd)
            return True
    
        hwnds = []
        win32gui.EnumWindows(callback, hwnds)
        for h in hwnds:
            win32gui.ShowWindow(h, win32con.SW_MINIMIZE)
    
    minimize_all()
    # Open a single exe using subprocess
    subprocess.Popen("C:\\path\\to\\exe.exe")
    

    This script uses the win32gui library to enumerate all open windows, and the win32con library to minimize them.