macosmacrosapplescriptautomatorkeyboard-maestro

AppleScript - Iterate all open applications / process and execute a menu command


I am trying to write an AppleScript to be triggered by hotkey in Keyboard Maestro on MacOS

What I want to do, and please do not suggest ANYTHING ELSE, such as hide all, or hide functionality. I am looking for minimize all open windows functionality, including the animation.

I can already do hide all.

So what I want to do is iterate all open windows, and trigger the menu option Window -> Minimize or if possible trigger minimize in a different manner.

Here is what I have so far but it is not fully working, only partially:

tell application "System Events"
    set currentProcesses to name of every application process whose visible = true
end tell

repeat with tmpProcess in currentProcesses

    tell application "System Events" to tell process tmpProcess

        set frontmost to true
        ---activate

        tell menu bar item "Window" of menu bar 1
            click menu item "Minimize" of menu 1
        end tell

    end tell

    delay 1

end repeat

Note, some applications will have a Minimise without a z for Minimize. . Would be good if the solution triggered some global minimize action rather than go through the menu system.


Solution

  • Another working example, best so far.

    tell application "System Events"
        set currentProcesses to name of every application process whose visible = true
    end tell
    
    repeat with tmpProcess in currentProcesses
    
        tell application "System Events" to tell process tmpProcess
            set frontmost to true
    
            try
                tell menu bar item "Window" of menu bar 1
    
                    try
                        click menu item "Minimize" of menu 1
                    on error
                        try
                            click menu item "Minimise" of menu 1
                        end try
                    end try
    
                end tell
    
            end try
    
            delay 0.1
    
            set visible to false
    
        end tell
    
    
    end repeat